Skip to content

Instantly share code, notes, and snippets.

@mattconnolly
Created November 28, 2012 04:04
Show Gist options
  • Star 63 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save mattconnolly/4158961 to your computer and use it in GitHub Desktop.
Save mattconnolly/4158961 to your computer and use it in GitHub Desktop.
RSpec basic authentication helper module for request and controller specs
module AuthHelper
def http_login
user = 'username'
pw = 'password'
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
end
end
module AuthRequestHelper
#
# pass the @env along with your request, eg:
#
# GET '/labels', {}, @env
#
def http_login
@env ||= {}
user = 'username'
pw = 'password'
@env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
end
end
# then in Rspec support:
RSpec.configure do |config|
config.include AuthRequestHelper, :type => :request
config.include AuthHelper, :type => :controller
end
# request specs need to explicitly pass the @env parameter along, eg:
describe "some request" do
http_login # or put this in a before :all
GET '/path', {}, @env
end
@ttcremers
Copy link

Great help this. thanks!

@lehresman
Copy link

I've modified this to create a slightly more convenient solution:
https://gist.github.com/lehresman/794f261708c82962763f

@lcezermf
Copy link

lcezermf commented Sep 3, 2015

Great job man! Thanks!

@rafaelcgo
Copy link

thanks for the examples! 👍

@bronson
Copy link

bronson commented Jan 14, 2016

If you're writing an integration test / request spec, just use https!:

      it 'should not allow access' do
        https!
        get '/data/properties'
        expect(response.body).to eq( {'error' => 'Unauthorized'}.to_json )
      end

@fwilkens
Copy link

Working with request specs with rspec-rails 3.x (3.7.2 in my case), you can pass the auth in the headers:

get '/path', headers: { 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) }

@luizcarvalho
Copy link

Thanks @mattconnolly, and thanks @fwilkens for update.

@BrennickL
Copy link

This modification worked for me

  module AuthHelper
    def http_login
      username = 'username'
      password = 'password'
      request.headers['AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(username,password)
    end
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment