rails attr_accessible rspec check

当我想测试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 

这样做有更好的方法吗?

…谢谢

这是在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) }