spatie/test-time
Control time in tests with Spatie TestTime—freeze or advance Carbon-based timestamps dynamically for time-sensitive assertions. Simplify testing date-dependent logic by manually adjusting time without altering real-world clocks. Works seamlessly with Carbon’s methods like addYear(), subDay(), or cus...
Install the package in your test environment only:
composer require spatie/test-time --dev
Start by importing the class in your tests:
use Spatie\TestTime\TestTime;
The most common first use case is freezing time at a known value for deterministic test assertions:
TestTime::freeze('2024-01-01 12:00:00');
// Now Carbon::now() always returns Jan 1, 2024 at noon
$this->assertEquals('2024', Carbon::now()->year);
Check the README and unit tests for immediate patterns.
protected function setUp(): void
{
parent::setUp();
TestTime::freeze('2024-02-15 09:00:00');
}
TestTime::addHours(2)->addMinutes(30);
$this->assertDatabaseCount('jobs', 1); // after job scheduled with delay
TestTime::freeze('Y-m-d', '2024-06-01'); // ignores time components
Carbon and CarbonImmutable.freeze() with unfreeze() in tearDown() if using class-level setup:
protected function tearDown(): void
{
TestTime::unfreeze();
parent::tearDown();
}
TestTime::freeze('2024-01-01 00:00:00', 'UTC');
freezeAtSecond() (1.2.0+) freezes to the current real second—useful for testing time-elapsed logic without hardcoding.unfreeze() happens reliably. Consider using ensureTestTimeIsReset() helper or Laravel’s WithoutTruncation trait alternatives.^2.63|^3.0). Mixing Carbon 3 with legacy helpers may cause subtle issues.useTestNow()—you can manually call Carbon::useTestNow() alongside it, but don’t mix approaches in the same test to avoid confusion.How can I help you explore Laravel packages today?