Benjamin Crouzier
Benjamin Crouzier

Reputation: 41865

When is the validator of email uniqueness trigerred?

I have a question about this test from the Michael Hartl tutorial :

Model:

class User < ActiveRecord::Base
  .
  .
  .
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                    uniqueness: true
end

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.email = @user.email.upcase
      user_with_same_email.save
    end

    it { should_not be_valid }
  end
end

My understanding of the uniqueness validator for the email is that it cannot be added twice in the database. But in this test, the User is just instantiated with a new, not a create.

So here is what I think happens:

What am I getting wrong ?

Upvotes: 1

Views: 25

Answers (1)

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41865

What really happens:

In before:

  • @user = User.new (just in memory)

In the describe:

  • user_with_same_email = @user.dup we have two users in memory
  • user_with_same_email.save we are inserting the first user in the db, so it should be valid, and it is ! But that's not what's being tested here

In the it:

  • should_not be_valid calls .valid? on @user, and since we've just inserted an user with the same email, @user is not valid. And so the test passes.

Upvotes: 1

Related Questions