自定义匹配器中的rspec mock should_receive

时间:2012-11-12 20:43:35

标签: rspec mocking match

我正在尝试在自定义匹配器中使用RSpec mock和should_receive。我想捕获should_receive引起的错误,从匹配器返回正确的值,并导致它输出我的自定义失败消息。

怎么做?或者也许我应该改变我的做法?

2 个答案:

答案 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.xRSpec::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)

另请参阅docs on custom matchers