应该匹配器和自定义错误消息

Shoulda-Matchers and Custom Error Messages

我正在尝试使用 shoulda 匹配器进行一些基本的 rspec 测试,但我遇到了一个我以前从未见过的错误。

我有一个名为 name 的独特属性,但出于项目需要的原因,我在 config/locales/en.yml 中用我自己的消息形式覆盖了默认 "has already been taken" 消息,而 Shoulda 没有好像不太喜欢

我收到了这条错误信息

 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"]

我在 shoulda-matchers 中是否缺少允许测试通过而不用担心错误消息的设置,或者这是模块的限制?

如果您不在匹配器上使用 with_message 方法,那么它 uses default message.

为了让你的测试工作,你应该覆盖 matcher's default message:

it { expect(subject).to validate_uniqueness_of(:name).with_message("has already been taken") }