如何为具有基本身份验证的 Rails 应用程序编写集成最小测试代码?
How can I write integration minitest code for a Rails app with basic authentication?
关于这个问题,Rails 指南和Rails 文档都不起作用。我写了这样的东西 运行 它
class PlacesTest < ActionDispatch::IntegrationTest
def test_places
get root_url
assert_response 200
end
end
但是我在 application_controller.rb
文件中有这一行:
http_basic_authenticate_with name: "dhh", password: "secret"
https://guides.rubyonrails.org/testing.html#what-to-include-in-your-functional-tests
此link好心建议
If you followed the steps in the Basic Authentication section, you'll need to add the following to the setup block to get all the tests passing:
request.headers['Authorization'] =
ActionController::HttpAuthentication::Basic.
encode_credentials('dhh', 'secret')
但是没有用。关注 link 也暗示同样的事情:
https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html
但是还是没有通过
E
Error:
PlacesTest#test_places:
NoMethodError: undefined method `headers' for nil:NilClass
test/integration/places_test.rb:6:in `setup'
你能帮帮我吗?
Rails 5 不再支持在控制器测试中访问 request
,因为控制器测试 类 继承自 ActionDispatch::IntegrationTest
,而它们继承自 ActionController::TestCase
在 Rails 4.
要在控制器测试中设置请求 header,您需要这样做:
get root_url, headers: { 'Authorization': ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
编辑:
指南是 out-dated,另请参阅 https://whosebug.com/a/52803443/7313509
关于这个问题,Rails 指南和Rails 文档都不起作用。我写了这样的东西 运行 它
class PlacesTest < ActionDispatch::IntegrationTest
def test_places
get root_url
assert_response 200
end
end
但是我在 application_controller.rb
文件中有这一行:
http_basic_authenticate_with name: "dhh", password: "secret"
https://guides.rubyonrails.org/testing.html#what-to-include-in-your-functional-tests
此link好心建议
If you followed the steps in the Basic Authentication section, you'll need to add the following to the setup block to get all the tests passing:
request.headers['Authorization'] =
ActionController::HttpAuthentication::Basic.
encode_credentials('dhh', 'secret')
但是没有用。关注 link 也暗示同样的事情:
https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html
但是还是没有通过
E
Error:
PlacesTest#test_places:
NoMethodError: undefined method `headers' for nil:NilClass
test/integration/places_test.rb:6:in `setup'
你能帮帮我吗?
Rails 5 不再支持在控制器测试中访问 request
,因为控制器测试 类 继承自 ActionDispatch::IntegrationTest
,而它们继承自 ActionController::TestCase
在 Rails 4.
要在控制器测试中设置请求 header,您需要这样做:
get root_url, headers: { 'Authorization': ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
编辑: 指南是 out-dated,另请参阅 https://whosebug.com/a/52803443/7313509