Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic values with RSpec mocks?

RSpec mocks can return multiple values.

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

How to return a dynamic value such as:

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

Always returns the first value.

Is it possible to have it evaluate the expression for each call to time?

like image 438
B Seven Avatar asked May 08 '15 23:05

B Seven


1 Answers

Just remove and_return and pass in block:

allow(clock).to receive(:time) do
  Time.now.to_i
end
like image 76
infused Avatar answered Nov 14 '22 23:11

infused