8

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?

MageeWorld
  • 402
  • 4
  • 14
  • Are you setting your original validation and error messages for name instead of 'validate_uniqueness_of(:name)' in Flavor model? – YTorii Oct 15 '16 at 01:59
  • @YTorii I'm sorry - I don't understand the question – MageeWorld Oct 15 '16 at 02:02
  • 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. – YTorii Oct 15 '16 at 03:02

1 Answers1

20

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") }
ole
  • 5,166
  • 5
  • 29
  • 57
  • Thank you. I did not see this myself when I looked at the shoulda github repository. I'm still familiarizing myself with it. – MageeWorld Oct 15 '16 at 17:27