Here is the rspec test to check the uniqueness of an email ( from http://ruby.railstutorial.org/chapters/modeling-users.html#code-validates_uniqueness_of_email_test )
require 'spec_helper'
describe User do
before do
@user = User.new(name: "Example User", email: "[email protected]")
end
.
.
.
describe "when email address is already taken" do
before do
user_with_same_email = @user.dup
user_with_same_email.save
end
it { should_not be_valid }
end
end
As the author mentioned, I added
class User < ActiveRecord::Base
.
.
.
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: true
end
to my user model and the tests pass.
But @user hasn't yet been saved to the database(I can't find @user.save statement anywhere is the code.) so, user_with_same_email is already unique since there is no other user with the same email in the database. Then how does it work?
I created something similar in the console. user_with_same_email.valid? returns false (with error "has already been taken"), but user_with_same_email.save still works. why?