Ruby on Rails Tutorial -- strange uses of upcase/downcase and
case-insensitivity
Working my way through Michael Hartl's excellent tutorial for Ruby on
Rails. I'm at the point where he creates a test that checks for duplicate
email addresses, and I'm a little confused about his use of upcase,
downcase, and case-insensitive checks.
The test (Listing 6.17) looks like this:
describe User do
before do
@user = User.new(name: "Example User", email: "user@example.com")
end
.
.
.
describe "when email address is already taken" do
before do
user_with_same_email = @user.dup
user_with_same_email.email = @user.email.upcase
user_with_same_email.save
end
it { should_not be_valid }
end
end
Note the call to upcase. All fine. But in his validity check (6.18), he
sets case sensitivity off.
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
What? Why did he convert the copy to uppercase if he was going to do a
case-insensitive validation?
Finally, in 6.20, he sets up a before_save block that converts a new
user's email to lowercase.
before_save { self.email = email.downcase }
That makes perfect sense, because you want lowercase in your database. But
I'm confused as to why he used uppercase in the test, given that the save
is going to convert the email address to lowercase anyway. Am I missing
something obvious?
No comments:
Post a Comment