Last active
November 1, 2021 11:00
-
-
Save majedbojan/c8d871c5a7a931c46b7fa7faa8bc40ef to your computer and use it in GitHub Desktop.
Add user Authentication to Rspec request
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
# frozen_string_literal: true | |
# Add `AuthenticationHelper` in spec/support/authentication_helper.rb | |
module AuthenticationHelper | |
def generate_token(user) | |
payload = { id: user.id.to_s } | |
JWT.encode payload, Rails.application.credentials.secret_key_base, 'HS256' | |
end | |
def sign_in(user) | |
request.headers['Authorization'] = generate_token(user) | |
end | |
end | |
RSpec.configure do |c| | |
c.include AuthenticationHelper | |
end | |
##---------------------------------------------- Usage ----------------------------------------------## | |
context '#show' do | |
before :each do | |
sign_in(user) | |
end | |
context 'when success' do | |
it 'returns success' do | |
get(:show, params: { id: 1 }) | |
expect(response).to be_successful | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment