访问请求规范中的请求对象 [英] Access to request object in request specs
问题描述
如何在对请求规范执行请求之前设置请求标头?
How can I set the request headers before doing the request on a request spec?
我正在移动控制器规范以使用 Rails 在我的 API 上请求规范.我坚持的一件事是我无法访问 request
对象来允许请求.
I'm moving controller specs to request specs on my API using Rails. One thing I'm stuck on is that I have no access to a request
object to allow the requests.
在我的控制器规范中,我可以访问我创建的用于为特定用户签名的方法:
On my controller specs, I have access to a method I created which signs a specific user:
def sign_in(user)
token = user.api_keys.first.token
# note the request object being used in the next line
request.env["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(token)
end
这在控制器规格上运行良好,我可以安全地做到:
This works fine on controller specs, I can safely do:
before { sign_in(user) }
it { post :endpoint, params }
但在请求规范中,request
对象不可用.如果我尝试:
But on a request spec, the request
object is not available.
If I try to:
before { sign_in(user) }
it { post "/api/endpoint", params }
我在辅助方法中得到 request
为 nil
.
I get request
on my helper method as nil
.
我知道我可以做到:
it { post "/api/endpoint", {"HTTP_AUTHORIZATION" => ... } }
但这在规范中似乎很混乱,特别是与控制器规范相比.
But this seems a lot of clutter in the spec, specially compared to a controller spec.
我已经按照 this answerActionDispatch::TestRequest::DEFAULT_ENV>,但它也不起作用(我得到一个 401
).
I've tried using ActionDispatch::TestRequest::DEFAULT_ENV
as suggested by this answer, but it didn't work too (I get a 401
).
推荐答案
如果您还没有为此使用 Rack::Test
那么您应该这样做.Rack::Test
比 Capybara 更适合测试 API 请求.它可以在你的 rspec/spec_helper.rb
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
当您配置为使用 Rack::Test 时,您可以在请求之前设置标头,如下所示:
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
这将在您的控制器中作为 request.headers['HTTP_AUTHORIZATION']
访问.
This will be accessible in your controller as request.headers['HTTP_AUTHORIZATION']
.
可以在此处找到此方法的源代码 - https://github.com/brynary/rack-test/blob/master/lib/rack/test.rb#L127-L141
The source code for this method can be found here - https://github.com/brynary/rack-test/blob/master/lib/rack/test.rb#L127-L141
这篇关于访问请求规范中的请求对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!