如何在RSpec中测试attr_accessible字段

War*_*les 23 rspec ruby-on-rails rspec2 rspec-rails

所以,我们一直在建立attr_accessibleattr_protected通过了我们的Rails应用程序3.2多领域.目前我们确实没有测试以确保这些字段受到保护.

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

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
Run Code Online (Sandbox Code Playgroud)

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

it { should_not be_accessible :field_name }
it { should be_accessible :some_field }
Run Code Online (Sandbox Code Playgroud)

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

shi*_*ara 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
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过示例将此代码放在`spec/support/be_accessible_matcher.rb`中 (4认同)

jui*_*dM3 28

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

it { should allow_mass_assignment_of :some_field }
it { should_not allow_mass_assignment_of :field_name }
Run Code Online (Sandbox Code Playgroud)

希望这有助于其他人.