Posted 11 days ago. Visible to the public. Linked content. Auto-destruct in 49 days

Updated: How to perform HTTP basic authentication in RSpec

Rewritten; added usage example for request specs.

Changes

  • -Do it like this in your controller specs:
  • +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.
  • - credentials = ActionController::HttpAuthentication::Basic.encode_credentials 'alice', 'secret'
  • - request.env['HTTP_AUTHORIZATION'] = credentials
  • - get :index
  • - # ...
  • -You may want to add `spec/support/auth_helper.rb`
  • +## Request specs
  • - module AuthHelper
  • - def basic_auth(user, password)
  • - credentials = ActionController::HttpAuthentication::Basic.encode_credentials user, password
  • - request.env['HTTP_AUTHORIZATION'] = credentials
  • - end
  • - end
  • +For request specs, use the `:header` option.
  • -and `include AuthHelper` to the corresponding specs.
  • +```ruby
  • +it 'requires authentication' do
  • + get '/'
  • + expect(response.status).to eq(401)
  • +end
  • -Your specs will then look prettier:
  • +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']`.
  • +
  • +```ruby
  • +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
  • +```
  • - basic_auth 'alice', 'secret'
  • - get :index
  • - # ...

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
11 days ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more