I ran into a little issue while writing functional tests in Rails 2.0, using the included HTTP authentication I’d find my controllers returning 401 errors since they weren’t authenticated. After poking around, I found a solution:
class Test::Unit::TestCase
def http_auth
@request.env[”HTTP_AUTHORIZATION”] = “Basic #{Base64.encode64(”foo:bar”)}”
end
end
def http_auth
@request.env[”HTTP_AUTHORIZATION”] = “Basic #{Base64.encode64(”foo:bar”)}”
end
end
Then, in my actual tests I could call:
http_auth
Thanks for the tip. You just saved me couple of hours of fighting with the tests.
Take Care.
Hugues
Thanks for the tip. You just saved me couple of hours of fighting with the tests.
Take Care.
Hugues
Ce n’est pas un problème! (That’s my year of Français I took coming out)
I definitely spent too much time trying to figure this out…it’s the simple things that are always a pain!
Ce n’est pas un problème! (That’s my year of Français I took coming out)
I definitely spent too much time trying to figure this out…it’s the simple things that are always a pain!
Thanks! Finally made my tests work..
Regards
Thanks! Finally made my tests work..
Regards
It’s always kind of cool when random people read your blog and you can help them
It’s always kind of cool when random people read your blog and you can help them
Ahh, yes! I’ve been looking for this too. Thanks!
Ahh, yes! I’ve been looking for this too. Thanks!
thanks for this. helped in our functional tests of our REST services using http basic auth.
thanks for this. helped in our functional tests of our REST services using http basic auth.
A few months late, I found this via the Google. A couple notes:
In case you’re unfamiliar with testing Rails, this goes in test/test_helper.rb
The function above doesn’t actually let you test HTTP Authentication. To do that you’ll need to do something like:
def authenticate_with_http(username, password)
@request.env[”HTTP_AUTHORIZATION”] =
“Basic #{Base64.encode64(“#{username}:#{password}”)}”
end
A few months late, I found this via the Google. A couple notes:
In case you’re unfamiliar with testing Rails, this goes in test/test_helper.rb
The function above doesn’t actually let you test HTTP Authentication. To do that you’ll need to do something like:
def authenticate_with_http(username, password)
@request.env[”HTTP_AUTHORIZATION”] =
“Basic #{Base64.encode64(“#{username}:#{password}”)}”
end
This was just what I needed!
Like unit testing you can do
def setup
http_auth
end
so all your test methods are authenticated.
Instead of using Base64 directly, it's better to use:
ActionController::HttpAuthentication::Basic.encode_credentials('username', 'password')