How to set request headers in rspec request spec?

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"}

I used this in Test::Unit:

@request.env['HTTP_ACCEPT'] = "*/*, application/youtube-client"
get :index

I'm adding this here, as I got majorly stuck trying to do this in Rails 5.1.rc1

The get method signature is slightly different now.

You need to specify the options after the path as keyword arguments, i.e.

get /some/path, headers: {'ACCEPT' => 'application/json'}

FYI, the full set of keywords arguments are:

params: {}, headers: {}, env: {}, xhr: false, as: :symbol


This is working for controller specs, not request specs:

request.headers["My Header"] = "something"