Home > Mobile >  Rails Rspec logging in with selected user
Rails Rspec logging in with selected user

Time:07-29

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

and i get:enter image description here

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

I get: enter image description here

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

  1. create user inside the login helper and call it outside the it block
       module 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
    
  2. Remove before(:each) block from login helper
       module 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
    
  • Related