[英]How to test attr_accessible fields in RSpec
So we have been setting up attr_accessible
and attr_protected
on many fields through out our Rails 3.2 app. 因此,我们通过Rails 3.2应用程序在许多字段上设置了
attr_accessible
和attr_protected
。 For now we really don't test to ensure that these fields are protected. 目前我们确实没有测试以确保这些字段受到保护。
So I decided to google some answers and stumbled upon this solution: 所以我决定谷歌一些答案,并偶然发现这个解决方案:
RSpec::Matchers.define :be_accessible do |attribute|
match do |response|
response.send("#{attribute}=", :foo)
response.send("#{attribute}").eql? :foo
end
description { "be accessible :#{attribute}" }
failure_message_for_should { ":#{attribute} should be accessible" }
failure_message_for_should_not { ":#{attribute} should not be accessible" }
end
But this solution only test's to see if the method is responding. 但是这个解决方案只测试方法是否响应。 What I need is a way for me to test that attributes can and can't be mass assigned.
我需要的是一种方法,让我测试属性可以和不能被大量分配。 I honestly love the syntax
老实说,我喜欢这种语法
it { should_not be_accessible :field_name }
it { should be_accessible :some_field }
Does anyone have a better solution to this problem? 有没有人有更好的解决方案来解决这个问题?
You can check if the attribute is on #accessible_attributes
list 您可以检查该属性是否在
#accessible_attributes
列表中
RSpec::Matchers.define :be_accessible do |attribute|
match do |response|
response.class.accessible_attributes.include?(attribute)
end
description { "be accessible :#{attribute}" }
failure_message_for_should { ":#{attribute} should be accessible" }
failure_message_for_should_not { ":#{attribute} should not be accessible" }
end
I was looking for something similar and then I was told about the shoulda-matcher allow_mass_assigment_of. 我正在寻找类似的东西,然后我被告知了shoulda-matcher allow_mass_assigment_of。 That ended up working for me without creating a custom matcher.
最终在没有创建自定义匹配器的情况下为我工作。
it { should allow_mass_assignment_of :some_field }
it { should_not allow_mass_assignment_of :field_name }
Hope this helps someone else. 希望这有助于其他人。
如果由于某种原因RSpec在juicedM3上面的答案绊倒就像我的那样,你可以这样做:
specify { expect { Model.new(unaccessible_attr: value) }.to raise_error(ActiveModel::MassAssignmentSecurity::Error) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.