4

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

YogiZoli
  • 870
  • 1
  • 9
  • 17
  • 3
    This error will get fixed a bit later in the tutorial when those attributes are marked as ok for mass assignment: "attr_accessible :name, :email, :password, :password_confirmation". (http://ruby.railstutorial.org/chapters/modeling-users?version=3.2#sec:has_secure_password) – aem Apr 29 '12 at 18:42

2 Answers2

7

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
zetetic
  • 47,184
  • 10
  • 111
  • 119
  • 1
    Thanks a lot, worked great! Can you tell me what is tap and when or how to use it? or give a link about it? thanks – YogiZoli Apr 03 '12 at 03:37
  • 2
    `tap` is documented here: http://ruby-doc.org/core-1.9.3/Object.html#method-i-tap. Note that pre-1.9, `tap` is available as an extension in Rails: http://apidock.com/rails/v2.3.8/Object/tap – zetetic Apr 03 '12 at 04:20
3

You can assign the attributes separately and not use mass assignment.

@user = User.new(name:"Example", email:"example@gmail.com")
@user.password = "foobar"
@user.password_confirmation = "foobar" 
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311