I'm facing the problem with logging in rspec with selected user. I've tried making controller module like that:
module ControllerMacros
def login(user)
before(:each) do
@request.env['devise.mapping'] = Devise.mappings[:user]
payload = { jti: SecureRandom.uuid, sub: user.id.to_s }
cookies['access_token'] = JWT.encode(payload, ENV['DEVISE_JWT_SECRET_KEY'], 'HS256')
sign_in user
end
end
end
The issue is that I'm either unbale to pass user in situation like that:
context 'as admin' do
let(:user) { create :user, :super_admin }
login user
before do
get :index
end
it { expect(response).to be_ok }
end
Or if I try something like that:
context 'as admin' do
let(:user) { create :user, :super_admin }
before do
login user
get :index
end
it { expect(response).to be_ok }
end
How can I make it work?
CodePudding user response:
you have created login
helper with before(:each)
block
In the first case, where you are calling login
helper outside the it
or before
block and passing user
instance created using let
. here user
is not available as scope of let
variables is inside the it
or before
block.
In the second case, where you are calling login
helper inside the before
block, but login
helper also adds before(:each)
block. I suspect due to calling of before(:each)
within before
it raises the error. similar issue reported here
Possible solutions
- create
user
inside thelogin
helper and call it outside theit
blockmodule ControllerMacros def login before(:each) do user = create :user, :super_admin @request.env['devise.mapping'] = Devise.mappings[:user] payload = { jti: SecureRandom.uuid, sub: user.id.to_s } cookies['access_token'] = JWT.encode(payload, ENV['DEVISE_JWT_SECRET_KEY'], 'HS256') sign_in user end end end context 'as admin' do login before do get :index end it { expect(response).to be_ok } end
- Remove
before(:each)
block fromlogin
helpermodule ControllerMacros def login(user) @request.env['devise.mapping'] = Devise.mappings[:user] payload = { jti: SecureRandom.uuid, sub: user.id.to_s } cookies['access_token'] = JWT.encode(payload, ENV['DEVISE_JWT_SECRET_KEY'], 'HS256') sign_in user end end context 'as admin' do let(:user) { create :user, :super_admin } before do login user get :index end it { expect(response).to be_ok } end