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: "[email protected]")
user2 = build(:user, email: "[email protected]")
expect(user2).to_not be_valid
end
app/model/user.rb
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: "[email protected]", created_at: nil, updated_at: nil> not to be valid
CodePudding user response:
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: "[email protected]")
user2 = build(:user, email: "[email protected]")
expect(user2).to_not be_valid
end