What's the best way to set Time.now
for the purpose of testing time-sensitive methods in a unit test?
相关问题
- Dependencies while implementing Mocking in Junit4
- How to unit test a reactive component where ngCont
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
相关文章
- How to replace file-access references for a module
- Ruby using wrong version of openssl
- How to mock methods return object with deleted cop
- What is a good way of cleaning up after a unit tes
-
EF6 DbSet
returns null in Moq - Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
I really like the Timecop library. You can do time warps in block form (just like time-warp):
(Yes, you can nest block-form time travel.)
You can also do declarative time travel:
I have some cucumber helpers for Timecop here. They let you do things like:
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):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
.I'm using RSpec and I did this: Time.stub!(:now).and_return(2.days.ago) before I call Time.now. In that way I'm able to control the time I used for that particular test case
Had the same issue, I had to fake time for a spec for a specific day and time just did that:
this will give you:
This kind of works and allows for nesting:
It could be slightly improved by undefing the stack and depth accessors at the end
Usage:
Also see this question where I put this comment as well.
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):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
.