Ruby Rspec Mock 相同实例在第一次和第二次调用中表现不同

Ehu*_*Lev 2 ruby rspec

我有一个看起来像这样的代码:

def call(some_id:)

          verify_before = @verify.call(some_id)
          return verify_before if verify_before.sucess?
          did_something = @processor.call(some_id)
          return did_something unless did_something.sucess?
          @verify.call(some_id)
end
Run Code Online (Sandbox Code Playgroud)

我想模拟@verify,所以第一次它会返回sucess?= false,第二次调用时它会返回true

最好的方法是什么?

spi*_*ann 5

是的,您可以告诉 RSpec 模拟在每次调用时返回不同的值。以下示例将false在第一次调用和true所有后续调用时返回:

allow(@verify).to receive(:sucess?).and_return(false, true)
Run Code Online (Sandbox Code Playgroud)

如何将其集成到您的测试中取决于您的设置方式@verify以及测试的总体外观。