gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:23:39 26 4
gpt4 key购买 nike

我有一个自定义匹配器,它在它的匹配 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com