1

我正在将 CanCanCan 与 Rolify 一起使用,并且正在尝试测试我的能力类授权。

测试非特权用户是否可以CRUD在系统中的其他用户测试失败

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(...)

但是我找不到任何原因导致我的能力类中的检查失败:

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

这是我的规格:

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
4

1 回答 1

2
expect(subject).to_not be_able_to(:crud, User) 

您正在引用用户模型,而不是那里的实例。使用 User.new 或其他持久化的 User 实例。

于 2014-11-15T15:37:40.673 回答