How to set request headers in rspec request spec?

前端 未结 10 1205
独厮守ぢ
独厮守ぢ 2020-12-04 08:33

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

request.accept = \"application/json\"

but in the request spec, \"request\"

相关标签:
10条回答
  • 2020-12-04 08:44

    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

    0 讨论(0)
  • 2020-12-04 08:46

    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)

    0 讨论(0)
  • 2020-12-04 08:47

    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
    
    0 讨论(0)
  • 2020-12-04 08:51

    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"}
    
    0 讨论(0)
  • 2020-12-04 08:56

    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

    0 讨论(0)
  • 2020-12-04 09:01

    Try something like:

    get :index, :format => 'json' 
    
    0 讨论(0)
提交回复
热议问题