如何在RSpec中测试attr_accessible字段

时间:2012-02-16 06:09:56

标签: ruby-on-rails rspec rspec2 rspec-rails

因此,我们通过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 }

有没有人能更好地解决这个问题?

3 个答案:

答案 0 :(得分:32)

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

答案 1 :(得分:28)

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

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

希望这有助于其他人。

答案 2 :(得分:1)

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

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