【问题标题】:Writing specs for CanCan Permissions为 CanCan 权限编写规范
【发布时间】:2011-07-27 21:58:01
【问题描述】:
我是 rpsec w Rails 3 的新手......我刚刚在我的 Rails 3 应用程序中添加了 CanCan 以获得权限。我想添加带有 rspec 的测试用例,但我不能 100% 确定它们应该放在哪里。
如果我想编写测试来检查权限。这些应该在控制器中吗?该模型?还有什么地方?
类似:
@user1 = belongs to @group
@user2 does not
@user1.should be_able_to(:destroy, @group.new(:user => user))
@user2. should_not be_able_to(:destroy, @group.new(:user => user))
谢谢
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
rspec
rspec2
cancan
【解决方案1】:
很好的问题,我认为它们应该存在于模型规格文件夹中,甚至应该添加为您正在测试的模型的描述块。类似的东西
# in user_spec.rb
describe "user abilities" do
let(:group) { Factory(:group) }
let(:user) { Factory(:user, :group => group) }
it "should be able to destroy his group" do
user.should be_able_to(:destroy, group)
end
it "should not be able to destroy other groups" do
Factory(:user).should_not be_able_to(:destroy, group)
end
# if be_able_to macro define its error message
# you could also do this kind of specs with
# automatic failure message and spec descriptions
subject { Factory(:user) }
it { should be_able_to(:destroy, subject.group) }
end
由于您指定用户能力,我认为user_spec.rb 是存储它们的最佳位置。
【解决方案2】:
我认为此类测试不应该属于模型,因为我不希望模型对象需要了解用户会话。我宁愿在控制器中处理该逻辑。
此外,虽然您可以创建一个能力规范来测试您的 cancan 配置,但不能证明您定义的授权规则已实际使用。您可以轻松地将 cancan 配置为禁止某个操作,在执行该操作之前从不检查授权,最终忽略您自己的规则。因此,我倾向于测试控制者在授权和未授权情况下的行为,而不是测试我的授权规则的实施。