Skip to content

Instantly share code, notes, and snippets.

@aarkerio
Last active January 22, 2025 18:56
Show Gist options
  • Save aarkerio/94d5270b73728c39bc8dd64b9a686005 to your computer and use it in GitHub Desktop.
Save aarkerio/94d5270b73728c39bc8dd64b9a686005 to your computer and use it in GitHub Desktop.
auth0 devise rspec authentication helper
def login_auth0(user)
OmniAuth.config.test_mode = true
# The mock_auth configuration allows you to set per-provider (or default)
# authentication hashes to return during integration testing.
opts = {
provider: 'auth0',
uid: user.auth0_id,
info: {
email: user.email,
name: 'auth0|d0584e3ab2d3816be9518a56',
nickname: 'Thurman DuBuque',
first_name: user.first_name,
last_name: user.last_name
},
credentials: {
token: user.auth0_id,
expires: true,
id_token: user.auth0_id,
token_type: 'Bearer',
refresh_token: '19f82075f7c69133452614bd177f4380'
},
extra: {
raw_info: {
email: '[email protected]',
email_verified: true,
iss: 'https://auth0.com/',
sub: 'auth0|d0584e3ab2d3816be9518a56',
aud: 'Auth012345',
iat: 1663896480,
exp: 1640375502
}
}
}
OmniAuth.config.mock_auth[:auth0] = OmniAuth::AuthHash.new opts
Rails.application.env_config['omniauth.auth'] = OmniAuth.config.mock_auth[:auth0]
Rails.application.env_config['devise.mapping'] = { user: Devise.mappings[:user] } # I'm using Auth0 with Devise
end
# Use it like
let(:admin_user) { Fabricate(:admin_user) }
before do
login_auth0 admin_user
end
it 'visit organizations screen' do
# you'd need next line if you "load" the Devise session in the Auth0 callback code:
# session[:userinfo] = request.env['omniauth.auth']
visit '/auth/oauth2/callback'
or you can add the session in the Rspec request:
get :foo_path, params: { foo: 'bar' }, session: {'user-info': OmniAuth::AuthHash.new(opts) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment