在 rspec 自定义匹配器中重用失败消息

23t*_*tux 7 ruby rspec

我有一个自定义匹配器,在其匹配块中使用期望(此处的代码已简化)

RSpec::Matchers.define :have_foo_content do |expected|
  match do |actual|
    expect(actual).to contain_exactly(expected)
    expect(actual.foo).to contain_exactly(expected.foo)
  end
end
Run Code Online (Sandbox Code Playgroud)

通常错误消息看起来像这样

       expected collection contained:  ["VLPpzkjahD"]
       actual collection contained:    ["yBzPmoRnSK"]
       the missing elements were:      ["VLPpzkjahD"]
       the extra elements were:        ["yBzPmoRnSK"]
Run Code Online (Sandbox Code Playgroud)

但是当使用自定义匹配器时,它只打印此内容,并且重要的调试信息会丢失:

expected MyObject to have_foo_content "foobar"
Run Code Online (Sandbox Code Playgroud)

那么,是否可以重新使用匹配块中的错误消息作为失败消息?我知道我可以提供自定义失败消息

failure_message do |actual|
  # ...
end
Run Code Online (Sandbox Code Playgroud)

但我不知道如何访问上述错误引发的失败消息。

Geo*_*roy 5

您可以RSpec::Expectations::ExpectationNotMetError在您的救援中match捕获失败的期望消息:

  match do |object|
    begin
      expect(object).to be_nil
    rescue RSpec::Expectations::ExpectationNotMetError => e
      @error = e
      raise
    end
  end

  failure_message do
    <<~MESSAGE
      Expected object to meet my custom matcher expectation but failed with error:
      #{@error}
    MESSAGE
  end
Run Code Online (Sandbox Code Playgroud)

不要忘记在 中重新加注rescue,否则不起作用