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: "[email protected]", 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?
First off, move the
admin?method toUsermodel so that it can be reused across Model-View-Controller.You can use this method wherever you have access to the instance of
User. Socurrent_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