Testing with Basic HTTP Authentication in Rails 2.0

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

Then, in my actual tests I could call:

http_auth

16 comments

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

    Take Care.

    Hugues

  2. Thanks for the tip. You just saved me couple of hours of fighting with the tests.

    Take Care.

    Hugues

  3. 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!

  4. 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!

  5. Thanks! Finally made my tests work..

    Regards

  6. Thanks! Finally made my tests work..

    Regards

  7. It’s always kind of cool when random people read your blog and you can help them :)

  8. It’s always kind of cool when random people read your blog and you can help them :)

  9. Ahh, yes! I’ve been looking for this too. Thanks!

  10. Ahh, yes! I’ve been looking for this too. Thanks!

  11. thanks for this. helped in our functional tests of our REST services using http basic auth.

  12. thanks for this. helped in our functional tests of our REST services using http basic auth.

  13. 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

  14. 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

  15. This was just what I needed!

    Like unit testing you can do

    def setup
    http_auth
    end

    so all your test methods are authenticated.

  16. Instead of using Base64 directly, it's better to use:

    ActionController::HttpAuthentication::Basic.encode_credentials('username', 'password')

Leave a comment