0

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?

1 Answers1

1

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
Amit Patel
  • 15,609
  • 18
  • 68
  • 106
  • Thank you so much for your time and explanation sir. I'm already using FactoryBot, but I totally forgot to update the test with it. If I may, I'd like to ask you more about this line let!(:user) { build (:user, role: 'admin') } this syntax belongs to FactoryBot? I'm starting at web dev and I only know FactoryBot with this syntax: create(:user, role: 'admin') – Italo Fasanelli Leomil May 02 '20 at 07:13
  • Learn here `build` vs `create` https://stackoverflow.com/questions/14098031/whats-the-difference-between-the-build-and-create-methods-in-factorygirl – Amit Patel May 02 '20 at 07:38
  • Got it now. Can't thank you enough for that. Have a great day! – Italo Fasanelli Leomil May 02 '20 at 07:41