Rspec and Rails 5 Request Specifications

I am starting a new project, the first with Rails 5.1.0. I have pb with my first request specification.

describe 'Users', type: :request do it 'are created from external data' do json_string = File.read('path/to/test_data/user_data.json') params = { user: JSON.parse(json_string) } headers = { "CONTENT_TYPE" => "application/json" } expect do post '/api/v1/users', params.to_s, headers end.to change { User.count }.by(1) expect(response.status).to eq 200 end end 

this parameter returns an error ArgumentError: wrong number of arguments (given 3, expected 1) . The official documentation doesn't say much.

If I pulled out .to_s and send the hash, like this:

 post '/api/v1/users', params, headers 

I got another error:

 ArgumentError: unknown keyword: user 

Any thought?

+5
source share
2 answers

I think they recently changed the syntax. Now it should use the args keywords. So something like this:

 post '/api/v1/users', params: params, headers: headers 
+10
source

Here is a small addition to the Sergio answer . If you upgrade from Rails 4 to Rails 5, you have a lot of tests and are not too interested in changing them - at least until you finish the upgrade - I found a way to get them to work with the old method signature.

In my spec_helper I added

 module FixLegacyTestRequests def get(path, par = {}, hdr = {}) process(:get, path, params: par, headers: hdr) end def post(path, par = {}, hdr = {}) process(:post, path, params: par, headers: hdr) end def put(path, par = {}, hdr = {}) process(:put, path, params: par, headers: hdr) end def delete(path, par = {}, hdr = {}) process(:delete, path, params: par, headers: hdr) end end 

and then I added this configuration for each test:

 RSpec.configure do |config| config.before :each do |example| extend(FixLegacyTestRequests) # to be removed at some point! end end 

My tests returned to work, and I think it should be safe, because it only applies to current testing and should not contaminate any gem code, such as a monkey patch.

+5
source

Source: https://habr.com/ru/post/1266736/


All Articles