Testing Time with Carbon and the Test Time Package

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

// we're now one year in the future

// 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:


// You can chain calls too

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


Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Full Stack Software Engineer
Atlanta, GA or Remote
Laravel/PHP Developer
Chicago, IL
Neon One
Software Engineer, Web Applications
Vaughan, ON, Canada
Blast Motion
Contract Services Software Engineer (Laravel | Vue | Tailwind)
Riverbed Technology
Senior Laravel Developer
Wilmington, NC
GE Software Inc.
Senior Full Stack Developer (PHP | Vue | DDD)
Charleston, SC