Skip to content

Instantly share code, notes, and snippets.

@lehresman
Last active February 16, 2022 22:29
Show Gist options
  • Save lehresman/794f261708c82962763f to your computer and use it in GitHub Desktop.
Save lehresman/794f261708c82962763f to your computer and use it in GitHub Desktop.
module AuthRequestHelper
def http_auth_as(username, password, &block)
@env = {} unless @env
old_auth = @env['HTTP_AUTHORIZATION']
@env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(username, password)
yield block
@env['HTTP_AUTHORIZATION'] = old_auth
end
def auth_get(url, params={}, env={})
get url, params, @env.merge(env)
end
def auth_post(url, params={}, env={})
post url, params, @env.merge(env)
end
def auth_put(url, params={}, env={})
put url, params, @env.merge(env)
end
def auth_patch(url, params={}, env={})
patch url, params, @env.merge(env)
end
def auth_delete(url, params={}, env={})
delete url, params, @env.merge(env)
end
end
RSpec.describe 'Clients API' do
include AuthRequestHelper
context 'GET index' do
it 'lists all clients for admin' do
http_auth_as 'admin', 'secret' do
auth_get '/clients.json'
expect(response.status).to eq 200
end
end
end
end
# Alternatively, you could just do an around filter so all your specs are authed by the same user
RSpec.describe 'Clients API' do
include AuthRequestHelper
around :each do |example|
http_auth_as 'admin', 'secret' do
example.run
end
end
context 'GET index' do
it 'lists all clients for admin' do
auth_get '/clients.json'
expect(response.status).to eq 200
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment