Access to request object in request specs

独自空忆成欢 提交于 2019-12-04 03:06:04

If you're not already using Rack::Test for this then you should be. Rack::Test is better suited than Capybara for testing API requests. It can be configured in your rspec/spec_helper.rb

RSpec.configure do |config|
  # ...
  config.include Rack::Test::Methods
end

When you're configured to use Rack::Test, you can set headers before the request like so:

it 'POST /api/enpoint authenticates successfully' do
  header 'Authorization', '...'
  post "/api/endpoint", params
  expect(last_response).to be_ok
end

This will be accessible in your controller as request.headers['HTTP_AUTHORIZATION'].

The source code for this method can be found here - https://github.com/brynary/rack-test/blob/master/lib/rack/test.rb#L127-L141

tycooon

If you use capybara for request specs, I guess you can set headers like suggested here, however it's better to perform the real log-in through the HTML form or whatever is the way to authenticate in your app, because request specs are higher level than controller ones, and that's why they normally do not allow you to manually set headers, cookies and other low level stuff.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!