Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set request headers in rspec request spec?

People also ask

What are request specs?

Request specs give you the ability to test what your application does, rather than how it does it. For example, instead of testing that the right template is rendered in a controller spec, with a request spec we can test that the content we are expecting to appear actually appears in the response body.

What is assigns RSpec?

assigns relates to the instance variables created within a controller action (and assigned to the view).

What is let in RSpec?

let generates a method whose return value is memoized after the first call. This is known as lazy loading because the value is not loaded into memory until the method is called. Here is an example of how let is used within an RSpec test. let will generate a method called thing which returns a new instance of Thing .


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"

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