【问题标题】:How to test attr_accessible fields in RSpec如何测试 RSpec 中的 attr_accessible 字段
【发布时间】:2012-03-07 13:30:07
【问题描述】:

因此,我们在 Rails 3.2 应用程序的许多领域都设置了 attr_accessible 和 attr_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 }

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

【问题讨论】:

  • 考虑使用 Permitters 或 Strong Parameters 代替批量分配安全性(attr_accessible + attr_protected),这在 Rails 4 中将消失。
  • 已经在生产中使用它。这是 ForbiddenAttributes 不是主流时的事情。

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


【解决方案1】:

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

【讨论】:

  • 您可以通过示例将此代码放在spec/support/be_accessible_matcher.rb中
  • 现在我为什么不去检查那个数组
  • shingara,如何在支持下执行be_accessible_matcher.rb中的代码? rspec spec/support 不执行任何操作。谢谢。
  • 代码未执行,如果您想回答,请提出真正的 SO 问题
【解决方案2】:

我一直在寻找类似的东西,然后我被告知了 shoulda-matcher allow_mass_assigment_of。这最终为我工作而无需创建自定义匹配器。

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

希望这对其他人有所帮助。

【讨论】:

  • 我想这或多或少是上面的实现方式。然而,我不知道这存在。为你投票
【解决方案3】:

如果由于某种原因,RSpec 像我的一样在上面的 juuddM3 的回答中遇到问题,您可以执行以下操作:

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

【讨论】:

  • 这是新期望风格的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多