travisjeffery / timecop

A gem providing "time travel", "time freezing", and "time acceleration" capabilities, making it simple to test time-dependent code. It provides a unified method to mock Time.now, Date.today, and DateTime.now in a single call.
MIT License
3.36k stars 223 forks source link

Timecop.scale to mock existing times #393

Closed coorasse closed 1 year ago

coorasse commented 1 year ago

Ok, I really did not find a good name for this issue, sorry. Please help me out here.

Situation: I have a method that sleeps 10 minutes

def first_method
  sleep(10.minutes)
end

The method is wrapped in a Timeout block:

def second_method
  Timeout(1.minute) do
    first_method
  end
end

I want to test that the Timeout works so I do:

expect { second_method }.to raise(TimeoutError)

I want my time to go faster. I don't want to wait 1 minute but maybe make it go 100x faster. I thought of wrapping it into:

Timecop.scale(60) do
  expect { second_method }.to raise(TimeoutError)
end

but this does not make the time to actually go faster. I also understand why. But I wonder if there's a solution for that.

coorasse commented 1 year ago

Of course, I can do:

SECOND_METHOD_TIMEOUT = 1.minute
def second_method
  Timeout(SECOND_METHOD_TIMEOUT) do
    first_method
  end
end

and mock it:

  stub_const('SECOND_METHOD_TIMEOUT', 0.1.second)
joshuacronemeyer commented 1 year ago

sorry I didn't have any suggestions on this that came to mind and I guess nobody else did either. I'm going to close this for lack of activity. Feel free to re-open if you need to.