简体   繁体   中英

Testing CanCanCan ability definition

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
expect(subject).to_not be_able_to(:crud, User) 

You are referencing User model, not instance there. Use User.new or another persisted User instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM