Ruby On Rails Lesson
Password and Confirmation
As seen in the mockup in Figure 6.1, we expect to have users confirm their passwords, a common practice on the web meant to minimize typos. We could enforce this at the controller layer, but it’s conventional to put it in the model and use Active Record to enforce the constraint. The method is to add password and password_confirmation attributes to the User model and then require that the two attributes match before the record is saved to the database. Unlike the other attributes we’ve seen so far, the password attributes will be virtual—they will only exist temporarily in memory and will not be persisted to the database.
We’ll start with respond_to tests for a password and its confirmation, as seen in Listing 6.27.
Notethat we’ve added :password and :password_confirmation to theinitialization hash for User.new:
We definitely don’t want users to enter a blank password, so we’ll add another test to validate password presence:
Since we’ll be testing password mismatch in a moment, here we make sure to test the presence validation by setting both the password and its confirmation to a blank string. This uses Ruby’s ability to make more than one assignment in a line. For example, in the console we can set both a and b to 3 as follows: