我正在使用ActiveAdmin和Cancancan开发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 我试图直接在浏览器中进行手动测试,而且功能也不起作用。
我不明白我错过了什么。有人知道我的代码出了什么问题吗?
我的项目
发布于 2016-05-14 10:34:15
在调查了几个小时之后,我发现问题来自与ActiveAdmin一样名字的变量(具有正确的能力),并且正在覆盖它们(能力很差)。
在我的ApplicationController中更改变量名,用能力修复了所有bug。
https://stackoverflow.com/questions/31636258
复制相似问题