Skip to content

Instantly share code, notes, and snippets.

@majedbojan
Last active November 1, 2021 11:00
Show Gist options
  • Save majedbojan/c8d871c5a7a931c46b7fa7faa8bc40ef to your computer and use it in GitHub Desktop.
Save majedbojan/c8d871c5a7a931c46b7fa7faa8bc40ef to your computer and use it in GitHub Desktop.
Add user Authentication to Rspec request
# 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