如何测试RSpec中的attr_accessible字段

因此,我们通过Rails 3.2应用程序在许多字段上设置了attr_accessibleattr_protected 。 目前我们确实没有测试以确保这些字段受到保护。

所以我决定谷歌一些答案,偶然发现这个解决方案:

 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 

但是这个解决方案只测试方法是否响应。 我需要的是一种方法,让我测试属性可以和不能被大量分配。 老实说,我喜欢这种语法

 it { should_not be_accessible :field_name } it { should be_accessible :some_field } 

有没有人有更好的解决方案来解决这个问题?

您可以检查该属性是否在#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 

我正在寻找类似的东西然后我被告知了shoulda-matcher allow_mass_assigment_of。 最终为我工作而没有创建自定义匹配器。

 it { should allow_mass_assignment_of :some_field } it { should_not allow_mass_assignment_of :field_name } 

希望这有助于其他人。

如果出于某种原因,RSpec正在跳上juicedM3的答案,就像我的那样,你可以这样做:

 specify { expect { Model.new(unaccessible_attr: value) }.to raise_error(ActiveModel::MassAssignmentSecurity::Error) }