Shoulda-Matchers and Custom Error Messages
Asked Answered
D

1

9

I am trying to do some basic rspec testing with shoulda matchers and I've come upon an error I haven't seen asked on SO before.

I have a unique attribute called name, but for reasons required of the project I have overwritten the default "has already been taken" message with my own form of the message in config/locales/en.yml and Shoulda doesn't seem to like it.

I received this error message

 Failure/Error: it { should validate_uniqueness_of(:name) }

   Flavor did not properly validate that :name is case-sensitively unique.
     Given an existing Flavor whose :name is ‹"Factory Flavor Namea"›,
     after making a new Flavor and setting its :name to ‹"Factory Flavor
     Namea"› as well, the matcher expected the new Flavor to be invalid and
     to produce the validation error "has already been taken" on :name. The
     record was indeed invalid, but it produced these validation errors
     instead:

     * name: ["This flavor name is already in the system"]
     * abbreviation: ["This abbreviation is already in use"]

Is there a setting I'm missing in shoulda-matchers that would allow the test to pass and not worry about the error message or is this a limitation of the module?

Deathful answered 14/10, 2016 at 22:40 Comment(3)
Are you setting your original validation and error messages for name instead of 'validate_uniqueness_of(:name)' in Flavor model?Localism
@Localism I'm sorry - I don't understand the questionDeathful
Oh, sorry. The error message says, validation of uniqueness is success, but error message is different from as expected(Rails' default error message for uniqueness). So I guess the oroginal error message is set manually in the model.Localism
S
21

If you don't use the with_message method on the matcher then it uses default message.

To make your test work you should override the matcher's default message:

it { expect(subject).to validate_uniqueness_of(:name).with_message("has already been taken") }
Spectrometer answered 15/10, 2016 at 3:20 Comment(1)
Thank you. I did not see this myself when I looked at the shoulda github repository. I'm still familiarizing myself with it.Deathful

© 2022 - 2024 — McMap. All rights reserved.