如何将动态值与 RSpec 模拟一起使用?

How to use dynamic values with RSpec mocks?

RSpec 模拟可以 return 多个值。

allow(die).to receive(:roll).and_return(1, 2, 3)

如何 return 动态值,例如:

allow(clock).to receive(:time).and_return Time.now.to_i

总是 return 第一个值。

是否可以让它对每次调用 time 的表达式求值?

只需删除 and_return 并传入块:

allow(clock).to receive(:time) do
  Time.now.to_i
end