我正在尝试在自定义匹配器中使用RSpec mock和should_receive
。我想捕获should_receive
引起的错误,从匹配器返回正确的值,并导致它输出我的自定义失败消息。
怎么做?或者也许我应该改变我的做法?
答案 0 :(得分:9)
答案是:
match do |obj|
# do some setup and mocks here
begin
RSpec::Mocks::verify # run mock verifications
true
rescue RSpec::Mocks::MockExpectationError => e
# here one can use #{e} to construct an error message
false
end
end
最后找到它here
答案 1 :(得分:0)
可接受的答案是正确的,但现在已过时。 As of RSpec 3.x,RSpec::Mocks::verify
no longer加注MockExpectationError
like it used to。
使用整体期望值,这对我来说效果很好:
RSpec::Matchers.define :expect_something_custom do |matcher_args|
supports_block_expectations
match do |block|
expect(…).to receive(…)
block.call
RSpec::Mocks.verify
end
end
expect { … }.to expect_something_custom(matcher_args)