How to perform HTTP basic authentication in RSpec

Posted About 13 years ago. Visible to the public.

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

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
Arne Hartherz
Last edit
Almost 2 years ago
Arne Hartherz
Keywords
basic, auth
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2011-04-07 14:23)