Testing with Basic HTTP Authentication in Rails 2.0

January 11, 2008

 
No Gravatar

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:

1
2
3
4
5
class Test::Unit::TestCase
 	def http_auth
	 @request.env[”HTTP_AUTHORIZATION”] = “Basic #{Base64.encode64(”foo:bar”)}”
	end
end

Then, in my actual tests I could call:

1
http_auth
  • Thanks for the tip. You just saved me couple of hours of fighting with the tests.

    Take Care.

    Hugues
  • Jonathan
    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!
  • Diego
    Thanks! Finally made my tests work..

    Regards
  • Jonathan
    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!
  • robert
    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
  • Jantzen Owens
    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')
blog comments powered by Disqus