为CanCan Permissions编写规范

时间:2011-07-27 21:58:02

标签: ruby-on-rails ruby-on-rails-3 rspec rspec2 cancan

我是rpsec w Rails 3的新手....我刚刚在我的Rails 3应用程序中添加了CanCan权限。我想添加测试用例,但我并不是百分之百确定他们应该居住的地方。

如果我想编写测试来检查权限。这些应该在控制器中吗?该模型?还有其他什么地方?

类似:

@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))

由于

2 个答案:

答案 0 :(得分:3)

不错的问题,我认为它们应该存在于model specs文件夹中,甚至可以作为您正在测试的模型的描述块添加。像

这样的东西
# 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是存储它们的最佳位置。

答案 1 :(得分:3)

我不认为这些测试应该属于模型,因为我不希望模型对象需要知道用户会话。我宁愿在控制器中处理这个逻辑。

此外,您可以创建一个ability_spec来测试您的cancan配置,但不能证明您实际使用的是您定义的授权规则。您可以轻松配置cancan以禁止操作,在执行该操作之前从不检查授权,最终忽略您自己的规则。因此,我倾向于在授权和未授权情况下测试控制器的行为,而不是测试我的授权规则的实现。

相关问题