public
Last active

RSpec basic authentication helper module for request and controller specs

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
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

Have you seen the basic_authorize method that is built into of Rack::Test?:
https://github.com/brynary/rack-test/blob/1b1e730866/lib/rack/test.rb#L142-L152

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'

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.