RSpec给出了ActiveModel :: MassAssignmentSecurity :: Error

时间:2012-04-03 02:50:38

标签: ruby-on-rails-3 rspec railstutorial.org mass-assignment

我正在关注Railstutorial.org并在使用Rspec时收到MassAssignment错误。

10) User when email format is invalid should be invalid
     Failure/Error: @user = User.new(name:"Example", email:"example@gmail.com",
     ActiveModel::MassAssignmentSecurity::Error:
       Can't mass-assign protected attributes: password, password_confirmation

可能是因为我尝试在RSpec中之前分配

  ...
  before do
     @user = User.new(name:"Example", email:"example@gmail.com", 
                                password: "foobar", password_confirmation: "foobar" )
  end

  subject { @user }
  ...

是否可以在开发或测试模式下禁用MassAssignment保护?或者当RSpec运行时? 任何帮助都会很棒!感谢

2 个答案:

答案 0 :(得分:7)

你可以避免批量分配:

before do
  @user = User.new(name:"Example", email:"example@gmail.com").tap do |u|
    u.password = "foobar"
    u.password_confirmation = "foobar"
  end
end

答案 1 :(得分:3)

您可以单独分配属性而不使用质量分配。

@user = User.new(name:"Example", email:"example@gmail.com")
@user.password = "foobar"
@user.password_confirmation = "foobar"