Testing Time with Carbon and the Test Time Package

Test Time is a package by Spatie that provides a helper for Carbon v2 to control the flow of time in PHPUnit tests.

Carbon is an excellent library to work with time in PHP projects. TheSpatie\TestTime\TestTimeclass contains a few functions that under the hood, manipulate the time that’s considered the current time by Carbon.

The readme provides a few quick examples that help you understand how to use it in your tests:

// the flow of time is frozen TestTime::freeze(); // we're now one year in the future TestTime::addYear(); // will report the real current year + 1 $year = (new Carbon())->format('Y');

Using this library, you can also progress the test time by calling the typical Carbon methods for adding or subtracting time:

TestTime::addMinute(); // You can chain calls too TestTime::addMonth(3)->addYear();

Under the hood, the TestTime class sets the time with Carbon::setTestNow(); . This package is useful for any PHP project using Carbon v2.

You can learn more about this package, get full installation instructions, and view the source code on GitHub at spatie/test-time.

Filed in: News