我正在使用ActiveAdmin和Cancancan开发Ruby on Rails项目。我为角色用户定义了一些功能,例如super_administrator
,administrator
或subscribers
。
在写了一些单元测试之后,我发现了能力不能正常工作,我无法弄清楚出了什么问题。
具体而言,我有一个简报模块,我只想administrator
或super_administrator
来管理它。
这是我的能力摘录:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # visitor user (not logged in)
alias_action :create, :read, :update, :destroy, to: :crud
if user.super_administrator?
# super_administrator privileges
elsif user.administrator?
# administrator privileges
elsif user.subscriber?
cannot :manage, Newsletter
else
cannot :destroy, :all
cannot :update, :all
cannot :create, :all
cannot :manage, Newsletter
end
end
end
我的测试:
# this test breaks for no reason
test 'should not destroy newsletter if logged in as subscriber' do
sign_in @subscriber
assert_no_difference 'Newsletter.count' do
delete :destroy, id: @newsletter
end
assert_redirected_to admin_dashboard_path
end
private
def initialize_test
@newsletter = newsletters(:one)
@subscriber = users(:alice)
end
此测试中断,因为即使我写了订阅者不管理时事通讯的能力,时事通讯也会被销毁。
奇怪的是,如果我测试订阅者的能力,一切正常:
# this test pass as expected by ability
test 'should test abilities for subscriber' do
sign_in @subscriber
ability = Ability.new(@subscriber)
assert ability.cannot?(:create, Newsletter.new), 'should not be able to create'
assert ability.cannot?(:read, Newsletter.new), 'should not be able to read'
assert ability.cannot?(:update, Newsletter.new), 'should not be able to update'
assert ability.cannot?(:destroy, Newsletter.new), 'should not be able to destroy'
end
我尝试直接在浏览器中手动测试,而且功能也不起作用。
我不明白我错过了什么。有人对我的代码有什么问题有任何疑问吗?
我的项目:
答案 0 :(得分:0)
经过数小时和数小时的调查,我发现问题来自与ActiveAdmin同名的变量(具有正确的能力)并且覆盖了它们(具有不良能力)。
在我的ApplicationController中更改变量名称修复了所有带有Abilities的错误。