测试CanCanCan能力定义

时间:2014-11-15 10:10:25

标签: ruby-on-rails rspec rolify cancancan

我正在使用CanCanCan和Rolify,我正在尝试测试我的Ability类授权。

当测试非特权用户是否可以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(...)

但是我找不到任何理由为什么我的Ability类中的检查失败了:

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

1 个答案:

答案 0 :(得分:1)

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

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