Read more

How to perform HTTP basic authentication in RSpec

Arne Hartherz
April 07, 2011Software engineer at makandra GmbH

The Basic Authentication header encodes username and password. Effectively, it's just Base64 plus a "Basic" prefix.
You can use ActionController::HttpAuthentication::Basic.encode_credentials for that, and put its result into the Authorization request header.

Request specs

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

For request specs, use the :header option.

it 'requires authentication' do
  get '/'
  expect(response.status).to eq(401)
end

it 'accepts valid credentials' do
  encoded_credentials = ActionController::HttpAuthentication::Basic.encode_credentials(username, password)
  get '/', header: { Authorization: encoded_credentials }
  expect(response.status).to eq(200)
end

Controller specs

In controller specs, you can put then into request.env['Authorization'].

it 'requires authentication' do
  get :index
  expect(response.status).to eq(401)
end

it 'accepts valid credentials' do
  encoded_credentials = ActionController::HttpAuthentication::Basic.encode_credentials(username, password)
  request.env['Authorization'] = encoded_credentials
  get :index
  expect(response.status).to eq(200)
end
Posted by Arne Hartherz to makandra dev (2011-04-07 16:23)