Statamic feature tests write to your real content folder
On this page
Statamic's content is flat files. Entries, globals, form submissions, all YAML and Markdown under content/ and storage/. That is why I like it. It is also why a Statamic feature test is not isolated the way a Laravel test is.
phpunit.xml swaps the database to SQLite in memory, the cache to array, the session to array. None of that touches the Stache. Form::find('contact')->submissions() in a test reads the real storage/forms/contact/ and saving or deleting a submission mutates it.
I learned this the usual way. A test created a submission, and its tearDown deleted submissions matching the test data to keep things tidy. The match was looser than I thought. It deleted 86 real stored submissions. They were tracked in git, so git restore storage/forms brought them back, and that is the only reason this is a blog post and not an apology.
The fix
Redirect the store before anything reads it. In the test's setUp:
$this->submissionsDirectory = storage_path('framework/testing/forms');
Stache::store('form-submissions')->directory($this->submissionsDirectory);
and delete that directory in tearDown. Aggregate stores pass the directory down to their child stores, so one call covers a whole collection. For an addon, statamic/cms ships Statamic\Testing\Concerns\PreventsSavingStacheItemsToDisk, which does it for every store at once.
Two rules I follow now:
- Never mass-delete items from a real form or collection in a tearDown, even filtered. Delete the temp directory instead.
- Any test that touches a form, an entry or a global gets the redirect in its base TestCase, not per test, so a new test cannot forget it.
The same idea on this site
This site is flat-file too, without Statamic. Its base TestCase points content.path at tests/Fixtures/content and the content cache at the array store before any test runs:
config([
'content.path' => base_path('tests/Fixtures/content'),
'content.cache_store' => 'array',
]);
The fixtures folder has four posts: two published, one draft, one dated 2099. The suite asserts on those counts, so a real post can never leak into a test and a test can never touch a real post. The lesson is the same whichever flat-file system you use: if the storage is a directory, the test needs its own directory.