How to check for incorrect env usage in Laravel with Pest

How to check for incorrect env usage in Laravel with Pest
Photo by Emile Perron / Unsplash

If you're using Laravel, then you should be familiar with the env() helper. This helper allows you to get the values from your .env file, or set a value if one doesn't exist.

You should only be calling env() in config files though. When you run config:cache, this tells the application to use values from your config files. If you're referencing env() in, for example, a Controller, then it'll return null.

With this in mind, I have the following test in my applications, which helps me ensure that env() isn't used anywhere but config files:

test('the codebase does not reference env variables outside of config files')
    ->expect('env')
    ->not->toBeUsed();

So this test will look inside my /app directory, and any sub-directories such as Controllers, Providers, Middleware etc... and check them all for env usage.

Made possible of course, with the wonderful Architecture Testing plugin in Pest