4

how do I test logging into a rails 3.1 app with http basic auth using rspec2 & capybara?

I'm using this;

 describe "GET 'index'" do
      it "should be successful" do
        request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
        get 'index'
        response.should be_success
      end
    end

but it gives me this error;

 NoMethodError:
            undefined method `env' for nil:NilClass
raphael_turtle
  • 7,154
  • 10
  • 55
  • 89

2 Answers2

17

Capybara comes with Rack::Test built in.

So, you can use the Rack::Test::Session.basic_authorize method to set the Authorization HTTP header field before making a request.

basic_authorize 'username', 'password'
get 'index'
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
ian
  • 12,003
  • 9
  • 51
  • 107
-1
@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")

This should be:

request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")

as request is not an instance variable.

Gazler
  • 83,029
  • 18
  • 279
  • 245
  • I'm using the solution here http://stackoverflow.com/questions/3768718/rails-rspec-make-tests-to-pass-with-http-basic-authentication – raphael_turtle Sep 16 '11 at 14:57