Laravel – testing environment file

It is often helpful to have different configuration values based on the environment the application is running in. In order to do that Laravel utilizes the DotEnv PHP library by Vance Lucas.

Unfortunately Laravel considers that application can run only in one environment per server and fetches all custom configuration parameters only from .env file. If you don’t have it, just copy .env.example

But there are times I need different values on the same machine. Most common use case is testing. I need one .env for my local development and then I would need a different database in my test cases.

Laravel way this can be done by switching .env to .env.local and then .env.testing to .env. After tests are finished files should be switched back again. Other way that is proposed is to include testing variables inside phpunit.xml file, check the section

 

Use different environment files

Checking Application.php (/vendor/laravel/framework/src/Illuminate/Foundation/Application.php) there is a protected variable $environmentFile that is set to ‘.env’.

Environment file is loaded during bootstrapping. Looking further you will also find a method calledloadEnvironmentFrom($file).

All you need to do now is call this method with proper environment file.

Since I only needed to switch files for testing I added .env.testing.example and .env.testing. I think it is wise to exclude any real config data from version control and exclude .env.testing (does .gitignore ring any bells?)

Lets call this method in /tests/TestCase.php

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Please prove me that you are not spamer :) * Time limit is exhausted. Please reload CAPTCHA.