如何在RSpec模拟中使用动态值?

B S*_*ven 4 ruby rspec mocking

RSpec模拟可以返回多个值。

allow(die).to receive(:roll).and_return(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

如何返回动态值,例如:

allow(clock).to receive(:time).and_return Time.now.to_i
Run Code Online (Sandbox Code Playgroud)

始终返回第一个值。

是否有可能让每次调用都评估表达式time

inf*_*sed 5

只需删除and_return并通过块:

allow(clock).to receive(:time) do
  Time.now.to_i
end
Run Code Online (Sandbox Code Playgroud)