我正在使用 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
这个测试会中断,因为即使我编写了订阅者不管理 Newsletter 的功能,Newsletter 也会被破坏。
奇怪的是,如果我测试订户的能力,一切正常:
# 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
我试图直接在浏览器中手动测试,但能力也不起作用。
我不明白我错过了什么。有人知道我的代码有什么问题吗?
我的项目:
- 红宝石 2.2.2
- 导轨 4.2.3
- ActiveAdmin 1.0.0 pre1
- 康康康 1.12.0