shoulda-matchers: Failing validate_uniqueness_of(:email)

I’m validating the email is unique, however the test should pass, but the message is incoherent and the error too.

My test: ` subject { build(:user) }

it { should validate_uniqueness_of(:email) }`

`

  1. User should validate that :email is case-sensitively unique Failure/Error: it { should validate_uniqueness_of(:email) }
   User did not properly validate that :email is case-sensitively unique.
     After taking the given User, whose :email is
     ‹"josiah_koelpin@wiegand.biz"›, and saving it as the existing record,
     then making a new User and setting its :email to a different value,
     ‹"JOSIAH_KOELPIN@WIEGAND.BIZ"›, the matcher expected the new User to
     be valid, but it was invalid instead, producing these validation
     errors:

     * email: ["ya ha sido tomado"]
 # ./spec/models/user_spec.rb:48:in `block (2 levels) in <top (required)>'

` The translation is in spanish, in english should be

has already been taken

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 15

Most upvoted comments

Okay. The reason why this is happening is that Devise overrides #email= to ensure that all emails are stored as lowercase in the database.

The matcher wants to create two records, one with an email address of “josiah_koelpin@wiegand.biz”, the other with an email of “JOSIAH_KOELPIN@WIEGAND.BIZ”. It expects this to work, because if it works, then it means your uniqueness validation is in place. However, because of Devise, the second user’s email gets changed to “josiah_koelpin@wiegand.biz”. So the matcher actually ends up trying to save two users with the same email address, and that doesn’t work, because the uniqueness validation doesn’t allow for that. So the matcher fails.

The message that you’re getting should be a little more descriptive, and to be honest, I’m not sure why it’s not – I added something extra to detect this in the latest version. In any case, try using:

it { should validate_uniqueness_of(:email).ignoring_case_sensitivity }

Thanks for the information, and it’s working now!. I used this.

it { should validate_uniqueness_of(:email).ignoring_case_sensitivity }

Yikes. That’s embarrassing. Thank you for proof reading my code. Next time I’ll send it it directly to you, instead of posting it publicly on github for everyone to see.

@batshoes This may not be it, but you have a validation on :user while your test is using :user_id. Try changing the validation to match?

Okay, cool. Glad I could help!

I’m going to keep this open to remind myself that we should make the user experience here better.