Using Ruby 2.1.0, Rails 4.0.2, MySQL, and OS X, I can't get the validator uniqueness: { case_insensitive: XXX }
to work right.
Yes, I realize this is almost, or perhaps precisely, identical to Rails 3. Validating email uniqueness and case sensitive fails. But the answer stream over there goes down a "don't do that" fork, and at least for pedagogic reasons I'd like to actually answer this question. Out of respect for the line taken over there, I've started a new question. Sorry if that's abusive.
My difficulty is that case_sensitive: true
and case_sensitive: false
produce the same results, even when (AFAICT) they oughtn't.
models/user.rb extract:
class User < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-.]+@akamai\.com\z/i
validates :email, presence: true, uniqueness: { case_sensitive: false }, format: {
with: VALID_EMAIL_REGEX,
message: "Must be an Akamai email address."
}
end
spec/models/user_spec.rb extract:
require 'spec_helper'
describe User do
before { @user = User.new(email: "giuseppe@akamai.com") }
subject { @user }
it { should be_valid }
context "email" do
describe "is already taken (caserifically)" 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
end
As written, the test passes (user_with_same_email is not valid). Cool.
However, if I change the validation's false
to true
, the test still passes (user_with_same_email is still invalid, presumably colliding). Uncool.
I know that MySQL/OSX is case-insensitive as regards table names (due to the case-insensitive underlying file system), but this doesn't extend to value comparisons, does it?
Ooo, just noticed the (unanswered) Ruby on Rails Tutorial - Michael Hartl - Test “User when email address is already taken”. I believe these are exact duplicates.