If you're working with Carbon dates, chances are your tests are going to fail at some point unless you're sure of the value returned from Carbon's now() function.
Whether you're using Carbon on it's own or as part of a framework, here's how to change the now()
value used globally with Carbon.
You can set what's returned when invoking now()
with the setTestNow()
method.
Carbon::setTestNow(Carbon::parse('16th November 1989 10:00'));
When you call now()
anywhere within your project, it'll return a Carbon object at this point in time. Simple!
I'd recommend not doing this globally, and instead defining it within every test for a bit more control.
function test_it_does_something_that_involves_a_date()
{
Carbon::setTestNow(Carbon::parse('16th November 1989 10:00'));
// ...
}
function test_it_does_something_else_that_involves_a_date()
{
Carbon::setTestNow(Carbon::parse('28th February 2017'));
// ...
}
If at any point you need to check whether the current date and time has been overriden with setTestNow()
, you can use the hasTestNow()
method, which lets you know if this is the case.
if (Carbon::hasTestNow()) {
// ...
}
And that's it. It's super easy to override the date and time that Carbon gives when you invoke the now()
method.