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

Ruby Rspec Mock Same instance to behave different in the first and second call

我的代码如下所示:

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

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

最好的方法是什么?

是的,您可以在每次调用时将 RSpec 模拟设置为 return 不同的值。以下示例将在第一次调用时 return false 并在以后的所有调用中 true

allow(@verify).to receive(:sucess?).and_return(false, true)

如何将其集成到您的测试中取决于您如何设置 @verify 以及您的测试总体上看起来如何。