Our most common flaky test failed at midnight on the last day of each month. The fix was to stop asking the system for the time.
What the test is for
Most of our flaky tests depended on the clock or on random data. Freezing time and seeding the generator fixed nearly all of them.
final class FrozenClock implements Clock {
public function __construct( private DateTimeImmutable $now ) {}
public function now(): DateTimeImmutable {
return $this->now;
}
}
$clock = new FrozenClock( new DateTimeImmutable( '2024-01-31 23:59:59' ) );
$invoice = new Invoice( $clock );
assertSame( '2024-02', $invoice->next_billing_month() );
Fixtures live next to the tests that use them and describe a real situation, like a customer with an expired card, rather than a pile of random fields. The snippet above is the whole thing; the version in our repository only adds tests.
Keeping the suite fast
- One behaviour per test
- Freeze the clock and seed randomness
- Name fixtures after real situations
- Keep the main suite under three minutes