Reputation: 41865
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:
@user = User.new
(just in memory)user_with_same_email = @user.dup
we have two users in memoryuser_with_same_email.save
we are inserting the first user in the db, so it should be valid, and yet the test it { should_not be_valid }
passes.What am I getting wrong ?
Upvotes: 1
Views: 25
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 memoryuser_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 hereIn 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