Create a gist now

Instantly share code, notes, and snippets.

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)
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)
# then in Rspec support:
RSpec.configure do |config|
config.include AuthRequestHelper, :type => :request
config.include AuthHelper, :type => :controller
# 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

Have you seen the basic_authorize method that is built into of Rack::Test?:


The Rack::Test authorize method didn't work for me (method not found), but this gist absolutely did the trick - thanks!


works great, thanks


Wish there was a way to +1 this - helped me a lot, thanks!


If you're using the force_ssl option in your application you might consider setting the https header in these methods

request.env['HTTPS'] = 'on'
@env['HTTPS'] = 'on'

Great help this. thanks!


I've modified this to create a slightly more convenient solution:


Great job man! Thanks!


thanks for the examples! 👍


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

      it 'should not allow access' do
        get '/data/properties'
        expect(response.body).to eq( {'error' => 'Unauthorized'}.to_json )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment