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

标签 ruby rspec

我有一个自定义匹配器,它在它的匹配 block 中使用期望(这里的代码被简化了)

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

通常错误消息看起来像这样
       expected collection contained:  ["VLPpzkjahD"]
       actual collection contained:    ["yBzPmoRnSK"]
       the missing elements were:      ["VLPpzkjahD"]
       the extra elements were:        ["yBzPmoRnSK"]

但是当使用自定义匹配器时,它只打印这个,并且重要的调试信息会丢失:
expected MyObject to have_foo_content "foobar"

那么,是否可以重新使用匹配 block 中的错误消息作为失败消息? 我知道我可以提供自定义失败消息
failure_message do |actual|
  # ...
end

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

最佳答案

你可以抢救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
不要忘记在 rescue 中重新加注, 否则不起作用

关于ruby - 在 rspec 自定义匹配器中重用失败消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58447648/

相关文章:

ruby-on-rails - Rails 引擎存在外键问题

ruby - 在 Rails 4 中写入流时如何使用 Rspec 和 ActionController::Live 进行测试?

ruby-on-rails - 使用 Rspec stub 调用 Rails.application.config_for?

ruby-on-rails - 使用 Capybara 检查复选框

ruby - 摆动假设 - ruby​​ 中字符串数组的组合或排列

StringIO 的 Ruby CSV BOM|UTF-8 编码

Ruby 2.3.1 Date.parse 在分隔符为空格字符时返回另一个日期

ruby-on-rails - Ruby 的 Paypal 自适应支付

c# - 将 Ruby 转换为 C#

ruby-on-rails - 在 rspec 请求规范中跨多个获取请求维护 session