What is the best way to write unit test for code that gets the current time? For example, some object can be created only on business days, other objects take the current time into account when checking permissions to perform certain actions, etc.
I think I should mock Date.today and Time.now. Is this the right approach?
Update: both solutions (a) Time.is and (b) Time.stubs (: now) .returns (t) work. (a) a very good approach, but (b) the solution will be more consistent with another test code.
In this question, the author asks for a general solution. For Ruby, in my version, the two solutions above are simpler and therefore better than retrieving code that receives the current date / time.
BTW I recommend using Chronic to get the required time, for example.
require 'Chronic'
mon = Chronic.parse("next week monday")
Time.stubs(:now).returns(mon)
source
share