I have a .env
file containing my database connection details, as is normal for Laravel 5. I want to override these for testing, which I can do in phpunit.xml
. However, doing this seems to go against the philosophy of .env
which is not to commit environmental configurations, particularly passwords.
Is it possible to have something like .env.testing
and tell phpunit.xml
to read from that?
A simple way to update the . env key value in laravel is to add the below code in the controller function where you want to change . env values. $key = 'VARIABLE_NAME'; $value = 'NEW VALUE'; file_put_contents(app()->environmentFilePath(), str_replace($key .
php has been deprecated since Laravel 5. Now, in L5, we have single . env file, where you store all your environment configuration. To define your environment, you should put APP_ENV=local to this file.
Copy your .env
to .env.testing
, then edit the .env.testing
file and change the APP_ENV
parameter to make it like this APP_ENV=testing
this way you will be able to specify your settings int this new file
In case you don't want to create a new .env.testing
file you have to specify your variables in the phpunit.xml
in the php section with the values you need, something like this
<php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/> <env name="QUEUE_DRIVER" value="sync"/> <env name="DB_CONNECTION" value="sqlite"/> <env name="DB_DATABASE" value="testing"/> </php>
Just use the key values in the name section and the value of that key in the value section.
For this example I am specifying phpunit to use an sqlite database with the name of testing.
By the way in config/database.php I added this 'default' => env('DB_CONNECTION', 'mysql'),
to use mysql by default unless I specify something diferent, as in this case.
You could override the .env
file being used in your TestCase
file, where the framework is booted for testing.
More specific:
tests/TestCase.php
/** * Creates the application. * * @return \Illuminate\Foundation\Application */ public function createApplication() { /* @var \Illuminate\Foundation\Application $app */ $app = require __DIR__ . '/../bootstrap/app.php'; $app->loadEnvironmentFrom('.env.testing'); // specify the file to use for environment, must be run before boostrap $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap(); return $app; }
All the tests extending TestCase
will use this configuration file.
Please note that any setting defined in phpunit.xml
will override this configuration.
Starting Laravel5.4, the createApplication
function is no longer found in tests\TestCase
. It has been moved to tests\CreatesApplication
trait.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With