How to fake Time.now?

前端 未结 14 1146
不知归路
不知归路 2020-12-02 11:47

What\'s the best way to set Time.now for the purpose of testing time-sensitive methods in a unit test?

14条回答
  •  心在旅途
    2020-12-02 12:42

    Depending upon what you are comparing Time.now to, sometimes you can change your fixtures to accomplish the same goal or test the same feature. For example, I had a situation where I needed one thing to happen if some date was in the future and another to happen if it was in the past. What I was able to do was include in my fixtures some embedded ruby (erb):

    future:
        comparing_date: <%= Time.now + 10.years %>
        ...
    
    past:
        comparing_date: <%= Time.now - 10.years %>
        ...
    

    Then in your tests then you choose which one to use to test the different features or actions based upon the time relative to Time.now.

提交回复
热议问题