How to set request headers in rspec request spec?

Sergey picture Sergey · Mar 11, 2012 · Viewed 79.4k times · Source

In the controller spec, I can set http accept header like this:

request.accept = "application/json"

but in the request spec, "request" object is nil. So how can I do it here?

The reason I want to set http accept header to json is so I can do this:

get '/my/path'

instead of this

get '/my/path.json'

Answer

awaage picture awaage · Mar 22, 2012

You should be able to specify HTTP headers as the third argument to your get() method as described here:

http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html#method-i-get

and here

http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html#method-i-process

So, you can try something like this:

get '/my/path', nil, {'HTTP_ACCEPT' => "application/json"}