Here is the failing test:
context "when password does not match confirmation" do
before { build(:user, :password_confirmation => 'mismatch') }
it { should_not be_valid }
end
I am using Factory Girl’s build method for this test suite.
My user model:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
validates :password_confirmation, presence: true
validates :password, presence: true, length: { minimum: 5 }
end
UPDATE: you don’t need to mark :password field with :confirmation => true when using has_secure_password. It’s taken care of: see source code: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/secure_password.rb
The validation is working just fine – I get the right error message when I try creating a new user at the console. So why is the test failing? Where is the bug?
The validation is not working just fine, you are not validating that the
password_confirmationmatches thepassword. See http://guides.rubyonrails.org/active_record_validations_callbacks.html#confirmation for more information.Also, you need to make sure that you’re actually testing what you want to be testing – your subject for these tests is
build(:user)when it needs to be thebuild(:user, password_confirmation: 'mismatch'). Change thebeforein your above code to asubject, to set the subject for the test correctly.