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
Do the time-warp
time-warp is a library that does what you want. It gives you a method that takes a time and a block and anything that happens in the block uses the faked time.
I allways extract
Time.now
into a separate method that I turn intoattr_accessor
in the mock.i just have this in my test file:
and in my Time_helper.rb file i have a
so when testing the time_right_now is overwritten to use what ever time you want it to be.
If you have ActiveSupport included, you could use http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html
Don't forget that
Time
is merely a constant that refers to a class object. If you're willing to cause a warning, you can always doPersonally I prefer to make the clock injectable, like so:
Or:
However, many prefer to use a mocking/stubbing library. In RSpec/flexmock you can use:
Or in Mocha: