Timecop And Date.parse Do Not Get Along
My first NYE in Berlin was quite awesome; red and green fireworks all night long. At the same time though, Timecop seemed to have a party of its own causing green and red specs as soon as the clock hit 00:00.
For those that are not familiar with Timecop, it’s a great gem that provides “test time-dependent code”. In other words, it mocks your your
A quick intro to
How about creating a method that takes a date as a parameter and compares it against current today’s date. The method simply returns
false depending on whether the date is in the future or past.
First let’s right a simple spec:
Now the method:
If you run the specs, both should pass.. today. Let’s see what will happen tomorrow when we run the specs again.
date is assigned to 11-2-2014,
Date.today will also be 11-2-2014. So, the first expecation should fail as
date is equal to
Timecop’s help, the issue can easily be resolved.
Timecop in our specs.
What we have done with
Timecop.freeze is to literally freeze
Date.today to a date we want, in this case the 10th of February, 2014. Now, our specs are bulletproof.
Timecop and Date.parse are not the best of friends
Date.parse takes a string and will try to convert it into a date. Ruby is kind of smart about it too. Few examples below:
The example we are interested in is the last one. If you pass a string that has no year reference,
Date.parse assumes is the current year and returns the date as such.
Let’s see now how the last example works with
Open up an
irb session and fire away:
Timecop has no effect when parsing dates with no reference to a year. Let’s clear something out first. You would never need to
freeze something like
Date.parse("20131120") as it’s already an immutable
Date object; immutable in the sense that the passing of time will not affect it’s state.
This caused the repo’s build to turn red the minute after NY as in many specs the above scenario occured.
A simple fix
There is a very simple fix to it. When using
Date.parse pass the current year as well:
I’m currently looking into patching this behavior and if it makes sense to make a pull request.
Note: The code runs with
Keep this sentence less than 13 words or it won't look good.