ruby-on-railscucumbertimecop

Timecop is not able to mock date correctly


I am using TimeCop Gem for testing time sensitive test cases. There is one file in the lib directory. It just contains string constants.

Example.

module DateStr
   SAMPLE = "Some date #{Date.current}"
end

In my cucumber test cases, this part of code does not get mock time. It picks system time. Why is that?


Solution

  • When DateStr was loaded, the SAMPLE constant was created and assigned the date that was present.

    I'd say that this is the wrong use case for constants, since they aren't supposed to change.

    EDIT.

    I wouldn't use constants for this behaviour. A hackish way would be to use lambdas:

    module DateStr
       SAMPLE = -> {"Some date #{Date.current}"}
    end
    DateStr::SAMPLE.call # This will evaluate to current date
    

    But this is not a good use case, since the value is not constant it self, instead for this kind of behaviour you should use a simple class method:

    module DateStr
       def self.sample
         "Some date #{Date.current}"
       end
    end