spatie/phpunit-snapshot-assertions
Add snapshot testing to PHPUnit. Assert strings, JSON, arrays, and objects against saved snapshots; first run writes snapshots, later runs compare and fail on regressions. Simple trait-based API (e.g., assertMatchesJsonSnapshot) for PHP and Laravel projects.
Route::json() or Http::get()).Stringable or View responses).spatie/phpunit-snapshot-assertions).use Spatie\Snapshots\MatchesSnapshots).assertMatchesJsonSnapshot()).$this->assertMatchesSnapshot($model->toArray(), new CustomDriver());
.gitignore for __snapshots__/ (add to CI exclusion lists).JsonDriver with JSON_PRETTY_PRINT to normalize output.CREATE_SNAPSHOTS, UPDATE_SNAPSHOTS) for CI/CD pipelines. Example:
# GitHub Actions
jobs:
test:
env:
CREATE_SNAPSHOTS: false
CREATE_SNAPSHOTS=false) to avoid race conditions in parallel test runners (e.g., Laravel’s --parallel or Paratest).assertMatchesHtmlSnapshot() for dynamic content like timestamps..gitignore)?UPDATE_SNAPSHOTS=true in PRs).composer update-snapshots in CI).JsonDriver, HtmlDriver) sufficient, or are custom drivers needed for domain-specific formats?uses(Spatie\Snapshots\MatchesSnapshots).Http::fake() or Route::json() to snapshot responses.assertMatchesTextSnapshot().$this->assertMatchesJsonSnapshot(Order::all()->toJson());
$response = $this->client->get('/api/orders');
$this->assertMatchesJsonSnapshot($response->getContent());
assertMatchesJsonSnapshot($response, 'orders-index')) for clarity.{
"scripts": {
"test": "phpunit",
"update-snapshots": "UPDATE_SNAPSHOTS=true phpunit",
"test:ci": "CREATE_SNAPSHOTS=false phpunit"
}
}
- run: composer test:ci
CREATE_SNAPSHOTS=false to avoid conflicts. Example for Laravel:
CREATE_SNAPSHOTS=false php artisan test --parallel
protected function getSnapshotId(): string {
return str_replace(["\r\n", "\r"], "\n", parent::getSnapshotId());
}
composer require --dev spatie/phpunit-snapshot-assertions
use Spatie\Snapshots\MatchesSnapshots;
class OrderTest {
use MatchesSnapshots;
public function test_index_returns_json() {
$response = $this->getJson('/api/orders');
$this->assertMatchesJsonSnapshot($response->getContent());
}
}
phpunit
CREATE_SNAPSHOTS=false phpunit
composer update-snapshots
protected function getSnapshotDirectory(): string {
return __DIR__ . '/../snapshots';
}
composer update-snapshots or UPDATE_SNAPSHOTS=true phpunit).main branch), but risks masking bugs.find __snapshots__ -type f -not -path "*/__snapshots__/*" -delete
assertMatchesFileSnapshot() for binary files (e.g., PDFs) to compare side-by-side.## Snapshots
To update snapshots:
1. Run `composer update-snapshots`.
2. Commit the changes with a message like "chore: update snapshots".
CREATE_SNAPSHOTS=false is unset).How can I help you explore Laravel packages today?