Search code examples
ruby-on-rails-3rspecrailstutorial.orgmass-assignment

RSpec gives ActiveModel::MassAssignmentSecurity::Error


I'm following Railstutorial.org and gets MassAssignment Error when using Rspec.

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

Probably because I try to assign before variables in RSpec:

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

  subject { @user }
  ...

Is it possible to disable MassAssignment protection in development or test mode? Or when RSpec is running? Any help would be great! Thanks


Solution

  • You could just avoid the mass assignment:

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