PHP 7: Maintaining and Upgrading Legacy Apps · Getting Legacy Code Under Test
Golden Master and Approval Tests
Snapshot large outputs like reports and HTML pages to refactor safely.
When code produces large outputs (HTML pages, PDF data, CSV exports), a golden master (approval) test runs it with fixed inputs, stores the output as an approved file, and compares future runs against it. Libraries like spatie/phpunit-snapshot-assertions automate this. They are coarse but quickly give a safety net over code you don't understand yet.
<?php
use PHPUnit\Framework\TestCase;
use Spatie\Snapshots\MatchesSnapshots;
final class InvoiceRenderTest extends TestCase
{
use MatchesSnapshots;
public function testInvoiceHtmlIsUnchanged(): void
{
$invoice = InvoiceFixtures::paidInvoiceWithThreeLines(); // deterministic data
$html = render_invoice_html($invoice, new DateTimeImmutable('2024-01-15'));
$this->assertMatchesHtmlSnapshot($html);
}
}
Common pitfalls
- Non-deterministic output (timestamps, random IDs) making snapshots flaky — inject fixed values.
- Blindly updating snapshots when tests fail.
- Relying only on snapshots long-term instead of focused tests.
Key points
- Snapshots give a fast safety net
- Make outputs deterministic
- Review snapshot diffs carefully
Further reading: spatie/phpunit-snapshot-assertions
Practice questions
What's the main weakness of golden master tests?
Answer
They tell you something changed but not whether the change is correct, and large snapshots tend to be approved without careful review.
How do you prevent snapshot tests from flaking?
Answer
Control all sources of variation: fixed dates/clocks, seeded randomness, stable ordering and fixed IDs in fixtures.
Open in the app to mark lessons complete, take notes and track your progress.