ruby-on-railsrspecactivemodelshoulda

Shoulda-Matchers and Custom Error Messages


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?


Solution

  • 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") }