如何在 RSpec 中测试 attr_accessible 字段 [英] How to test attr_accessible fields in RSpec
问题描述
因此,我们在 Rails 3.2 应用程序中的许多字段上设置了 attr_accessible
和 attr_protected
.目前我们确实没有测试以确保这些字段受到保护.
So we have been setting up attr_accessible
and attr_protected
on many fields through out our Rails 3.2 app. 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?
推荐答案
您可以检查该属性是否在#accessible_attributes
列表中
You can check if the attribute is on #accessible_attributes
list
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
这篇关于如何在 RSpec 中测试 attr_accessible 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!