gpt4 book ai didi

ruby-on-rails - 访问请求规范中的请求对象

转载 作者:数据小太阳 更新时间:2023-10-29 06:50:46 26 4
gpt4 key购买 nike

如何在根据请求规范执行请求之前设置请求 header ?

我正在移动 Controller 规范以使用 Rails 请求我的 API 规范。我坚持的一件事是我无法访问 request 对象来允许请求。

在我的 Controller 规范中,我可以访问我创建的对特定用户进行签名的方法:

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

这在 Controller 规范上运行良好,我可以放心地这样做:

before { sign_in(user) }
it { post :endpoint, params }

但是在请求规范中,request 对象不可用。如果我尝试:

before { sign_in(user) }
it { post "/api/endpoint", params }

我在我的辅助方法上得到 request 作为 nil

我知道我能做到:

it { post "/api/endpoint", {"HTTP_AUTHORIZATION" => ... } }

但这在规范中似乎很困惑,特别是与 Controller 规范相比。

我已经按照 this answer 的建议尝试使用 ActionDispatch::TestRequest::DEFAULT_ENV ,但它也不起作用(我得到一个 401)。

最佳答案

如果您还没有为此使用 Rack::Test,那么您应该这样做。 Rack::Test 比 Capybara 更适合测试 API 请求。它可以在你的 rspec/spec_helper.rb

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

当您配置为使用 Rack::Test 时,您可以像这样在请求之前设置 header :

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

这将在您的 Controller 中作为 request.headers['HTTP_AUTHORIZATION'] 访问。

此方法的源代码可在此处找到 - https://github.com/brynary/rack-test/blob/master/lib/rack/test.rb#L127-L141

关于ruby-on-rails - 访问请求规范中的请求对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22850898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com