When we expect a changed value, we need to tell the test runner to update the existing snapshots instead of failing the test. This is possible by adding a-d --update-snapshots flag to the phpunit command.

> ./vendor/bin/phpunit -d --update-snapshots
OK (1 test, 1 assertion)

As a result, our snapshot file returns "bar" instead of "foo".

<?phpreturn'bar';

File snapshots

The MatchesSnapshots trait offers two ways to assert that a file is identical to the snapshot that was made the first time the test was run:

The assertMatchesFileHashSnapshot($filePath) assertion asserts that the hash of the file passed into the function and the hash saved in the snapshot match. This assertion is fast and uses very little disk space. The downside of this assertion is that there is no easy way to see how the two files differ if the test fails.

The assertMatchesFileSnapshot($filePath) assertion works almost the same way as the file hash assertion, except that it actually saves the whole file in the snapshots directory. If the assertion fails, it places the failed file next to the snapshot file so they can easily be manually compared. The persisted failed file is automatically deleted when the test passes. This assertion is most useful when working with binary files that should be manually compared like images or pdfs.

Customizing Snapshot Ids and Directories

Snapshot ids are generated via the getSnapshotId method on the MatchesSnapshot trait. Override the method to customize the id. By default, a snapshot id exists of the test name, the test case name and an incrementing value, e.g. Test__my_test_case__1.

Example: Renaming the __snapshots__ directory to snapshots

Writing Custom Drivers

Drivers ensure that different types of data can be serialized and matched in their own way. A driver is a class that implements the Spatie\Snapshots\Driver interface, which requires three method implementations: serialize, extension and match.