Rspec-rails: Upgrading to Rails 5: posting raw JSON and new params format

Created on 2 Jul 2016  ·  9Comments  ·  Source: rspec/rspec-rails

I updated my controller specs to use the new syntax with params and I am using the rails-controller-testing gem too, but I'm not sure what key or format I'm supposed to use to get this raw JSON post to no longer throw a deprecation notice while still posting it as raw JSON:

post :callback, { id: 777 }.to_json, format: :json
DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only
keyword arguments in future Rails versions.

Examples:

get :show, params: { id: 1 }, session: { user_id: 1 }
process :update, method: :post, params: { id: 1 }
 (called from block (4 levels) in <top (required)> at /private/var/www/redacted/spec/controllers/payments_controller_spec.rb:114)

My controller is expecting raw JSON to be parsed like this:

def callback
  data = JSON.parse(request.body.read)
  ...
end

Keep in mind that I cannot alter the controller or the fact that this is receiving raw JSON since it's a callback for an external 3rd party service.

Most helpful comment

Try: post :callback, body: { id: 777 }.to_json, format: :json you basically can't pass in a string etc anymore as far as I know

All 9 comments

Try: post :callback, body: { id: 777 }.to_json, format: :json you basically can't pass in a string etc anymore as far as I know

That did it, thanks!

In Rails 5.0 you have to do post :update, params: { id: user_id }, body: { id: 777 }.to_json, as: :json. Note – not format: json but as: :json, otherwise correct request mime-type won't be set.

In Rails 5.0 you have to do post :update, params: { id: user_id }, body: { id: 777 }.to_json, as: :json. Note – not format: json but as: :json, otherwise correct request mime-type won't be set.

You saved my life

It should work also this way: post :update, params: { id: user_id, id: 777 }, as: :json

This is working for me:

post :update, params: { id: user_id, id: 777 }, as: :json

But when I try using body: directly:

post :update, body: { id: user_id, id: 777 }.to_json, as: :json

I get:

 ArgumentError:
       unknown keyword: body

I'm using rails 5.2.2 and rspec 3.8.0

@pimlottc-gov this is entirely dependant on your Rails version, as mentioned above you must use the params route.

@pimlottc-gov solution worked for me in rails 6.0.0 and rspec 3.9.0. 🍾

@aaronwbrown I'm using post '/routename', params: params, as: :json but when I try to add headers, eg post '/routename', params: params, as: :json, headers: headers neither the params nor the headers get through to the controller. Anyone know how to get the headers in there too? I tried putting the headers arg in different places to no avail

Was this page helpful?
0 / 5 - 0 ratings