Ruby On Rails Lesson
To enforce uniqueness of email addresses (so that we can use them as usernames), we’ll be using the :unique option to the validates method. But be warned: There’s a major caveat, so don’t just skim this section—read it carefully.
We’ll start, as usual, with our tests. In our previous model tests, we’ve mainly used User.new, which just creates a Ruby object in memory, but for uniqueness tests we actually need to put a record into the database.13 The (first) duplicate email test appears in Listing 6.18.
The method here is to make a user with the same email address as @user, which we accomplish using @user.dup, which creates a duplicate user with the same attributes. Since we then save that user, the original @user has an email address that already exists in the database, and hence should not be valid.
We can get the new test in Listing 6.18 to pass with the code in Listing 6.19
We’re not quite done, though. Email addresses are case-insensitive—email@example.com goes to the same place as FOO@BAR.COM or FoO@BAr.coM—so our validation should cover this case as well. We test for this with the code in Listing 6.20.
Here we are using the upcase method on strings (seen briefly in Section 4.3.2). This test does the same thing as the first duplicate email test, but with an upper-case email address instead. If this test feels a little abstract, go ahead and fire up the console: