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: "[email protected]", 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: '[email protected]', 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
has_secure_password validations: false # This is the key to the solution
validates :password, presence: true, length: { minimum: 6 } # Or an length you want
The Long story
The docs and the source code say:
If you don’t need the confirmation validation, just don’t set any value to the password_confirmation attribute and the the validation will not be triggered.
But they also say:
Validations for presence of password on create, confirmation of password (using a +password_confirmation+ attribute) are automatically added. If you wish to turn off validations, pass validations: false as an argument. You can add more validations by hand if need be.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With