Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unique email address on User model unit test failing

I have a user model that expects an email address to be unique however the models spec is failing:

spec/user_spec.rb

it "has a unique email" do
  user1 = build(:user, email: "example@email.com")
  user2 = build(:user, email: "example@email.com")
  expect(user2).to_not be_valid
end

app/model/user.rb

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class User < ApplicationRecord
      
  validates :email, format: {with: URI::MailTo::EMAIL_REGEXP}, presence: true, uniqueness: true

end
User has a unique email
     Failure/Error: expect(user2).to_not be_valid
       expected #<User id: nil, email: "example@email.com", created_at: nil, updated_at: nil> not to be valid

>Solution :

The uniqueness validation happens by performing an SQL query into the model’s table, searching for an existing record with the same value in that attribute.

So, you just build two users in memory, neither of them is saved to database. Save the user1 to database, and then validate user2.

A possible change to your test may look like this:

it "has a unique email" do
  user1 = create(:user, email: "example@email.com")
  user2 = build(:user, email: "example@email.com")
  expect(user2).to_not be_valid
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading