Last active
February 16, 2022 22:29
-
-
Save lehresman/794f261708c82962763f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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