Łukasz Korol Łukasz Korol - 2 months ago 7x
Ruby Question

How to get proper email uniqueness in RSpec

Rspec throws errors:

1) Client uniqueness validates uniqueness of email
Failure/Error: expect(subject).to validate_uniqueness_of :email

Client did not properly validate that :email is case-sensitively unique.
After taking the given Client, whose :email is
‹"jaleel_wehner@okonwiegand.name"›, and saving it as the existing
record, then making a new Client and setting its :email to a different
value, ‹"JALEEL_WEHNER@OKONWIEGAND.NAME"›, the matcher expected the
new Client to be valid, but it was invalid instead, producing these
validation errors:

* pesel: ["This pesel is already in database"]
* email: ["This email is already in database"]

In model I have implemented uniqueness and case-sensitive: false for email.

validates :email, presence: true,
uniqueness: { case_sensitive: false },
format: { with: VALID_EMAIL_REGEX }

I also have implemented method, that all email downcase before validation.

def downcase_email
self.email = email.downcase if email.present?
before_validation :downcase_email

Why matcher expected that new Client will be valid? It should be invalid.

subject { FactoryGirl.build(:client) }
it 'validates uniqueness of email' do
expect(subject).to validate_uniqueness_of :email

Client has a valid factory. I tried find good solution, but I haven't found anything that would solve my problem.

FactoryGirl.define do
factory :client do
pesel { Faker::Number.number(11) }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
date_of_birth { Faker::Time.between('1970-01-01', '2000-12-31') }
email { Faker::Internet.email }
password { Faker::Internet.password }
type 'Client'


FactoryGirl has the following example for your issue within it's documentation

sequence :email do |n|

factory :invite do
  invitee { generate(:email) }

Edit after your updates:

The issue is the matcher validate_uniqueness_of. You have to adjust case_sensitive for the matcher too. So it should be validate_uniqueness_of(:email).case_insensitive