spatie/phpunit-snapshot-assertions
Add snapshot testing to PHPUnit with simple assertions for JSON, XML, and text. First run creates snapshots; later runs compare outputs and fail on regressions. Ideal for verifying serialized data and responses with minimal test boilerplate.
Install via composer require --dev spatie/phpunit-snapshot-assertions, then use the Spatie\Snapshots\MatchesSnapshots trait in your test class. Start with simple string or JSON assertions:
public function test_rendered_output() {
$this->assertMatchesJsonSnapshot(json_encode(['status' => 'ok']));
}
On first run, this creates a snapshot file (e.g., __snapshots__/TestName__test_rendered_output__1.json). Subsequent runs will pass if output matches; otherwise, they fail with a diff. Use phpunit -d --update-snapshots (or UPDATE_SNAPSHOTS=1) to refresh snapshots after intentional changes.
assertMatchesJsonSnapshot(), assertMatchesHtmlSnapshot(), or assertMatchesXmlSnapshot() over generic assertMatchesSnapshot() for better formatting and semantic assertions.'user-view') to avoid brittle auto-incrementing IDs, especially for tests with multiple snapshots or flaky auto-increment behavior.tests/__snapshots__ (default).php artisan test --parallel with CREATE_SNAPSHOTS=false in CI to avoid write conflicts.assertMatchesFileSnapshot() to persist the actual file on failure for visual diffing.Driver interface to handle domain formats (e.g., YamlDriver, PDFTextDriver). Implement serialize(), extension(), and match() to control formatting and comparison logic..gitattributes, mark snapshot directories as binary (e.g., tests/**/__snapshots__/** binary) to prevent Git from normalizing line endings on Windows/macOS.CREATE_SNAPSHOTS=false in CI to fail fast if snapshots are missing or out of sync—do not allow snapshot creation in CI pipelines.UPDATE_SNAPSHOTS=1 without code review; manually verify diffs to catch unintended regressions. Consider using phpunit --filter=test_.*named.* to update only specific snapshots.phpunit --debug to see exact file paths of snapshots; failed snapshots (e.g., for assertMatchesFileSnapshot()) are written side-by-side for manual inspection.'order-api-response') avoid this fragility but require manual naming discipline..gitignore entries only for temp files (e.g., .tmp.png), never for snapshots themselves.spatie/pixelmatch-php; use threshold tuning (e.g., 0.05 for strict, 0.2 for flaky UIs) and verify pixel-diff files are generated on failure.How can I help you explore Laravel packages today?