Reputation: 4752
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'
Upvotes: 142
Views: 103901
Reputation: 2769
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 for rspec 2:
get '/my/path', nil, {'HTTP_ACCEPT' => "application/json"}
Or like this for rspec 3:
get '/my/path', params: {}, headers: { 'HTTP_ACCEPT' => "application/json" }
Upvotes: 143
Reputation: 1451
This is working for controller specs, not request specs:
request.headers["My Header"] = "something"
Upvotes: 25
Reputation: 17323
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
Upvotes: 9
Reputation: 13929
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)
Upvotes: 12
Reputation: 1722
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
Upvotes: 31
Reputation: 630
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
Upvotes: 11
Reputation: 119
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"}
Upvotes: 9
Reputation: 1087
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"}}
Upvotes: 2
Reputation: 1905
I used this in Test::Unit:
@request.env['HTTP_ACCEPT'] = "*/*, application/youtube-client"
get :index
Upvotes: 40