当我想测试属性是否为/不是时无障碍使用 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
有更好的方法吗?
...thx
这是 Rails 教程中完成属性可访问性测试的方式 http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#code:attr_accessible_user_id_test,我觉得都挺好的。因此,在您的情况下,可以稍微修改测试代码,如下所示:
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
如果这不是您想要的,当您询问是否有“更好的方法”时,您能否让我们更好地了解您想要什么样的解决方案?
Edit
您可能感兴趣应该使用 ActiveModel 匹配器 https://github.com/thoughtbot/shoulda-matchers#activemodel-matchers,这会将代码清理为每个测试仅一行。就像是:
it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)