ruby-on-railsrspecsimplecov

How do I unit test the current_user RoR


I have this method to check if the user is admin:

def admin?
  current_user.admin == true
end

The unit test is:

require 'rails_helper'

describe StubController do
  describe '.admin?' do
    it "should tell if the user is admin" do
      user = User.create!(email: "i@i.com", password:'123456', role: "admin", name: "Italo Fasanelli")

      result = user.admin?

      expect(result).to eq true
    end
  end
end

The problem is, simplecov is telling me that this part current_user.admin == true is not covered.

How do I test the current_user in this test?


Solution

  • First off, move the admin? method to User model so that it can be reused across Model-View-Controller.

    class User < ApplicationRecord
      def admin?
        role == 'admin'
      end
    end
    

    You can use this method wherever you have access to the instance of User. So current_user.admin? would also work across views and controller.

    Now you should write test for model not the controller. Also I noticed that you create user model object manually instead of using Factory. Use FactoryBot to create required instances for testing.

    Here is a quick spec assuming there is factory is set for user

    require 'rails_helper'
    
    RSpec.describe User, type: :model do
      describe '.admin?' do
        context 'user has role set as admin' do
          let!(:user) { build(:user, role: 'admin') }
    
          it 'returns true' do
            expect(user).to be_admin
          end
        end
    
        context 'user has role set as non admin' do
          let!(:user) { build(:user, role: 'teacher') }
    
          it 'returns true' do
            expect(user).not_to be_admin
          end
        end
      end
    end