【问题标题】:How to test for mass assignment errors in Rspec and Rails 4?如何测试 Rspec 和 Rails 4 中的质量分配错误?
【发布时间】:2013-12-07 13:02:47
【问题描述】:

我最近将我的 Rails 应用程序从 Rails 3 升级到了 4,但这个 Rspec 测试不再通过:

# spec/models/user_spec.rb:

require 'spec_helper'

describe User do

  it "should not allow access to admin" do
    expect do
      User.new(:admin => true)
    end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
  end

end

我收到此错误:

Failure/Error: end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
NameError: uninitialized constant ActiveModel::MassAssignmentSecurity

我怀疑这在某种程度上是由于切换到 Rails 4 的 strong 参数

我现在如何测试批量分配错误?

感谢您的帮助。

【问题讨论】:

  • 使用强参数,这种测试应该在控制器级别完成,而不是模型级别。
  • @Baldrick:好的,既然我已经在我的控制器测试中测试了这个,我可以安全地放弃上面的测试吗?
  • 是的。这篇文章可能会让你信服:weblog.rubyonrails.org/2012/3/21/strong-parameters
  • @Baldrick:我有一种预感。感谢您确认。

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


【解决方案1】:

正如 Baldrick 正确指出的那样,Rails 4 中没有必要在 Rspec 模型测试中测试质量分配问题。 Rails 4 的Strong Parameters 的整个想法是将所有功能移至控制器。

【讨论】:

    【解决方案2】:

    要使您的测试通过,您需要添加 config.active_record.mass_assignment_sanitizer = :strict to
    config/aplication.rb 并将 gem https://github.com/rails/protected_attributes 添加到 Gemfile。

    如果你想测试强参数阅读这篇文章http://pivotallabs.com/rails-4-testing-strong-parameters/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多