Testing HTTP Basic Authentication Middleware in ruby-grape/grape
This test suite validates the HTTP Basic Authentication strategy implementation in Grape middleware. It ensures proper authentication handling and response behavior for different authorization scenarios in a Rack-based application.
Test Coverage Overview
Implementation Analysis
Technical Details
Best Practices Demonstrated
ruby-grape/grape
spec/grape/middleware/auth/strategies_spec.rb
# frozen_string_literal: true
describe Grape::Middleware::Auth::Strategies do
describe 'Basic Auth' do
let(:app) do
proc = ->(u, p) { u && p && u == p }
Rack::Builder.app do
use Grape::Middleware::Error
use(Grape::Middleware::Auth::Base, type: :http_basic, proc: proc)
run ->(_env) { [200, {}, ['Hello there.']] }
end
end
it 'throws a 401 if no auth is given' do
get '/whatever'
expect(last_response).to be_unauthorized
end
it 'authenticates if given valid creds' do
get '/whatever', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('admin', 'admin')
expect(last_response).to be_successful
expect(last_response.body).to eq('Hello there.')
end
it 'throws a 401 is wrong auth is given' do
get '/whatever', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('admin', 'wrong')
expect(last_response).to be_unauthorized
end
end
end