with rails 4 i use has_secure_password in my user model , trick says that if i don't set the :password_confirmation it will never be triggered but why when i run the test i get error : Password confirmation can't be blank as the following :
Failures:
1) User
Failure/Error: it { should be_valid }
expected #<User id: nil, name: "joe", email: "joe@mail.com", created_at: nil,
updated_at: nil, password_digest: "$2a$04$mcRr/msgYQR3kBVc3kv/m.UotBJuJuSXZKMw
/eHTvU87..."> to be valid, but got errors: Password confirmation can't be blank
my test file look like :
require 'spec_helper'
describe User do
before { @user = User.new(name: 'joe', email: 'joe@mail.com', password: 'foo') }
subject { @user }
#....
#....
describe "when password is not present" do
before { @user.password = "" }
it { should_not be_valid }
end
end
why i get this error, there is a solution for that ? thank's
Long story short
The Long story
The docs and the source code say:
But they also say:
Item #1 is not a complete description. We need to turn off all validation and add our own validation rules to make this work like as described in point #2.
I spent sometime on this and got a lesson: find the source code when you are confused. This seems to be a painful way or hard way, but sometime it's the right way.
Change your test's
before
line to this:That should fix it.
What this is about:
You know how when you create a new account on pretty much any website, they ask you to make up a password and enter it twice? That's what this is. When you create a new user,
has_secure_password
wants the password twice to make sure you didn't make a typo.If
password
!=password_confirmation
, it will throw an exception and the user won't be created.Again, this is only used on user creation. You don't need to enter two passwords in the login form or anything else. You don't have to add this field to your model or DB.
If you have a user creation form, and you don't want to have a
password_confirmation
field, then you don't have to. You can setpassword_confirmation = password
in your controller, before you call save or whatever.But for User creation, the
password_confirmation
must be present.I did this as a temporary measure until I get this app from Rails 4.0.13 to 4.1 and beyond: