132
votes

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'
10

10 Answers

132
votes

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

I used this in Test::Unit:

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

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

20
votes

This is working for controller specs, not request specs:

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

With RSpec 3 you can use the following syntax

get my_resource_path, params: {}, headers: { 'HTTP_ACCEPT' => "application/json" }

As described in the official Rspec documentation (the link points to v3.7)

9
votes

I have to set up headers separately

request.headers["Accept"] = "application/json"

Trying sending it via get/delete/.... is complete garbage in rails4 and causing pain in my head because it is never send as header but as parameter.

{"Accept" => "application/json"}
9
votes

Using rspec with Rack::Test::Methods

header 'X_YOUR_HEADER_VAR', 'val'
get '/path'

The header var will come through as X-Your-Header-Var

8
votes

To send both xhr: true and headers, I had to do e.g.:

my_headers = { "HTTP_ACCEPT": "application/json" }
get my_path, xhr: true, headers: my_headers
2
votes

Your question was already answered but in case you want to POST something to another action you have to do this:

post :save, {format: :json, application: {param1: "test", param2: "test"}}
2
votes

Try something like:

get :index, :format => 'json'