Skip to main content

Testing your example file

.env.example is the template every new environment is set up from. A key set twice in it is copied into each of them, where nobody looks at it again. Two tests hold it, and the second is the one that matters: the first can only ever be green, and the second proves it could turn red.

use Pushery\ProductionPreflight\Env\EnvFile;

it('keeps .env.example free of keys set twice', function (): void {
$example = EnvFile::read(base_path('.env.example'));

expect($example)->toBeInstanceOf(EnvFile::class, '.env.example is missing, so the test read nothing');
expect(count($example->assignments))->toBeGreaterThan(20, '.env.example holds hardly any assignment');
expect($example->duplicates())->toBe([]);
});

it('would see a key set twice in .env.example', function (): void {
$example = EnvFile::read(base_path('.env.example'));
$first = $example->assignments[0]->key;

$planted = EnvFile::parse('.env.example', $example->bytes."\n{$first}=planted\n");

expect($planted->duplicates())->toHaveCount(1)
->and($planted->duplicates()[0]->key)->toBe($first);
});

Set the count in the first test near the number of keys your file has. A test that runs over an empty or missing file reports exactly what a test over a correct one reports, and the count is what tells them apart.

EnvFile reads a file the way the checks do: comments and the export prefix are skipped, a value may contain =, an empty value counts, and a quoted value that runs over several lines is not read as keys. duplicates() lists each key set more than once with its lines, valuesDiffer() says whether the lines disagree, and effective() is the line that applies, the last one.