About this matter, Rails guides and Rails documentation both didn't work. I wrote something like this and ran it
class PlacesTest < ActionDispatch::IntegrationTest
def test_places
get root_url
assert_response 200
end
end
But I have this line on application_controller.rb
file:
http_basic_authenticate_with name: "dhh", password: "secret"
https://guides.rubyonrails.org/testing.html#what-to-include-in-your-functional-tests
This link suggests kindly
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')
But it didn't work. Following link also suggests the same thing:
https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html
But still test didn't pass.
E
Error:
PlacesTest#test_places:
NoMethodError: undefined method `headers' for nil:NilClass
test/integration/places_test.rb:6:in `setup'
Could you help me?
Accessing request
in controller tests is no longer supported in Rails 5, since controller test classes are inheriting from ActionDispatch::IntegrationTest
, while they were inheriting from ActionController::TestCase
in Rails 4.
To set request header in controller tests, you need to do this:
get root_url, headers: { 'Authorization': ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
Edit: The guides are out-dated, see also https://stackoverflow.com/a/52803443/7313509