如何让模拟消耗一些时间rspec

How to make mock consume some time rspec

我希望 rspec 消耗一定的时间然后 return。例如,下面是一条逻辑线,表示我希望 rspec 在 1 秒后模拟对 some_method 和 return 的调用。可能吗?

expect(MyClass).to receive(:some_method).consume_time(1).and_return(true)

使用timecop to manipulate time. Use a block模拟方法体。

expect(MyClass).to receive(:some_method) do
  Timecop.travel(Time.now + 1)
  true
end

请注意,如果您要模拟 some_method 来测试可能应该是 allow 的其他内容。

使用不带块的Timecop具有全局效果。请务必调用 Timecop.return 来重置时间流,也许在 after hook 中以确保它发生。您甚至可以将其全局添加到 RSpec,这样您就永远不会忘记。

RSpec.configure do |config|
  config.after { Timecop.return }
end

使用 block 模拟方法体。

expect(MyClass).to receive(:some_method) do
  sleep(1)
  true
end