在我的测试环境中,Cancan无法建立规则。
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.is_admin?
can :manage, :all
end
....
end
end
启动开发控制台并执行以下操作
u = User.where(role: "admin").first
u.ability.can?(:read, Order) #true
a = Ability.new(u)
a.instance_values["rules"] #gives [0] #<CanCan::Rule:0x000055f2637ece48 @match_all=false, @base_behavior=true, @actions=[:read], @subjects=[Order(id: integer, ....
表示一切正常。规则已设定。在rails c test
中执行相同操作
a.instance_values["rules"]
为空
u = User.where(role: "admin").first
u.ability.can?(:read, Order) #false
a = Ability.new(u)
a.instance_values["rules"] #gives []
结果是测试
RSpec.describe Ability do
describe 'User' do
describe "abilities" do
context "when is an Admin" do
subject(:admin){ AdminAbility.new(create(:admin_user)) }
it do
puts admin.can? :read, Order #false
puts admin.ability.can? :read, Order #false
puts admin.instance_values["rules"] # nil ?
expect(admin).to be_able_to(:read, Order)
end
it {expect(admin).to be_able_to(:read, User) }
end
end
end
end
对
并不意外** Failure/Error: it {expect(admim).to be_able_to(:read, Order)}
expected to be able to :read Order(...)**
在测试运行期间,rules
哈希中不存在instance_values
键。
为开发(和生产)环境正确生成了。
(我已经针对角色和Adminuser测试了FactorySetup,这不是问题)
设置: 导轨:3.2.22.2 规格:3.8 CanCan:1.6.10