rails attr_accessible rspec check

equ*_*nt8 6 ruby-on-rails shoulda attr-accessible ruby-on-rails-3

当我想测试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
Run Code Online (Sandbox Code Playgroud)

这样做有更好的方法吗?

...谢谢

Pau*_*nti 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
Run Code Online (Sandbox Code Playgroud)

如果这不是您想要的,那么当您询问是否有"更好的方法"时,您能否让我们更好地了解您所采用的解决方案?

编辑

您可能对Shoulda ActiveModel匹配器感兴趣,它会将代码清理为每个测试只有一行.就像是:

it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }
Run Code Online (Sandbox Code Playgroud)