6

当我想测试属性是否 / 无法使用 RSpec访问时,我正在这样做

class Foo
  attr_accesible :something_else
end

describe Foo do
  it('author should not be accessible')    {lambda{described_class.new(:author=>true)}.should raise_error ActiveModel::MassAssignmentSecurity::Error}
  it('something_else should be accessible'){lambda{described_class.new(:something_else=>true)}.should_not raise_error ActiveModel::MassAssignmentSecurity::Error}
end

有更好的方法吗?

...谢谢

4

1 回答 1

7

这是 Rails 教程中进行属性可访问性测试的方式,我认为这非常好。因此,在您的情况下,测试代码可以稍微修改为:

describe Foo do
  describe "accessible attributes" do
    it "should not allow access to author" do
      expect do
        Foo.new(author: true)
      end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end

    it "should allow access to something_else" do
      expect do
        Foo.new(something_else: true)
      end.to_not raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end
  end
end

如果这不是您想要的,当您询问是否有“更好的方法”时,您能否更好地了解您所追求的解决方案?

编辑

您可能对Shoulda ActiveModel 匹配器感兴趣,它可以将代码清理为每次测试仅一行。就像是:

it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }
于 2012-08-07T15:51:07.517 回答