Rails/Rspec Make tests pass with http basic authentication

benoitr picture benoitr · Sep 22, 2010 · Viewed 30.6k times · Source

Here my http basic authentication in the application controller file (application_controller.rb)

before_filter :authenticate

protected

def authenticate
  authenticate_or_request_with_http_basic do |username, password|
    username == "username" && password == "password"  
  end
end

and the default test for the index action of my home controller (spec/controllers/home_controller_spec.rb)

require 'spec_helper'

describe HomeController do

describe "GET 'index'" do
  it "should be successful" do
    get 'index'
    response.should be_success
  end
end

Test doesn't run because of the authentication method. I could comment "before_filter :authenticate" to run them but I would like to know if there is way to make them worked with the method.

Thank you!

Answer

iwasrobbed picture iwasrobbed · Mar 8, 2011

Update (2013): Matt Connolly has provided a GIST which also works for request and controller specs: http://gist.github.com/4158961


Another way of doing this if you have many tests to run and don't want to include it everytime (DRYer code):

Create a /spec/support/auth_helper.rb file:

module AuthHelper
  def http_login
    user = 'username'
    pw = 'password'
    request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
  end  
end

In your test spec file:

describe HomeController do
  render_views

  # login to http basic auth
  include AuthHelper
  before(:each) do
    http_login
  end

  describe "GET 'index'" do
    it "should be successful" do
      get 'index'
      response.should be_success
    end
  end

end

Credit here