I'm using CanCanCan with Rolify and I´m trying to test my Ability class authorization.
When testing if a unprivileged user can CRUD
other users in the system the test fails
1) Ability a guest user should not be able to manage others
Failure/Error: expect(subject).to_not be_able_to(:crud, User)
expected not to be able to :crud User(...)
But I can't find any reason why the check in my Ability class fails:
class Ability
include CanCan::Ability
def initialize(user = User.new)
alias_action :create, :read, :update, :destroy, :destroy_multiple, to: :crud
# What is wrong?
can :crud, User, id: user.id
if user.has_role?(:admin)
can :manage, User
end
end
end
This is my spec:
require 'rails_helper'
require 'cancan/matchers'
RSpec.describe Ability do
let(:user) { create(:user) }
subject { Ability.new(user) }
context "a guest user" do
it "should be able to manage self" do
expect(subject).to be_able_to(:crud, user)
end
it "should not be able to manage others" do
expect(subject).to_not be_able_to(:crud, User)
end
end
end
You are referencing User model, not instance there. Use User.new or another persisted User instance.