DMA's avatar
Level 2

Two different environment configs (local and testing) for the same machine

Like many, I have one machine that I develop my applications on and also use for testing. I'm using a MySQL database for development (and will be doing for production), but for my tests, I want to use an SQLite database.

I know that PHPUnit will switch the environment to 'testing', but how can I tell it which configuration options to use?

In config/database.php I have set the default database connection name to:

'default' => env('DB_DRIVER', 'mysql'),

and in my .env file, I have:

APP_ENV=local
APP_DEBUG=true

DB_DRIVER=mysql
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

So, that's the local environment taken care of.

When PHPUnit runs, and it switches the env to testing, I want it to use SQLite.

I want to have a second environment config file for testing, like so:

APP_ENV=testing
APP_DEBUG=true
DB_DRIVER=sqlite

How can I create this file, and define the DB_DRIVER? It looks like .env.testing files are no longer supported, so I'm wondering how I can have a different set of config options for different environments on a single machine.

0 likes
6 replies
DMA's avatar
DMA
OP
Best Answer
Level 2

To answer my own question, these can be set using the phpunit.xml file:

<php>
        <env name="APP_ENV" value="testing"/>
        <env name="DB_DRIVER" value="sqlite"/>
    </php>
DMA's avatar
Level 2

Actually, looks like I spoke too soon. For example, if I want to run migrations under the 'testing' env, Laravel won't read the settings from the phpunit.xml file.

So whilst PHPUnit may be able to use the right DB, there's no easy way for Laravel to access a testing config that I can work out. Any ideas?

There's a method called 'loadEnvironmentFrom()' in Illuminate\Foundation\Application.php but it's never called anywhere.

anouarabsslm's avatar

you may try this trick:

'default' => $app->environment()=='testing'?'sqlite':'mysql',
DMA's avatar
Level 2

This isn't how @JeffreyWay does this though is it?

I've seen screencasts he's recorded where he has seeded a database using --env=testing, with the migration hitting an SQLite database, whereas the application would otherwise work with a MySql database.

Those 'testing' env settings must be getting stored somewhere, else how would Laravel know what the configuration is?

andy's avatar

I haven't tried this with L5 but for L4 I have

.env .env.local

files that I was checking against.

DMA's avatar
Level 2

Looks like creating a folder with the environment name in the config directory works. I can't seem to be able to find a reference to this anywhere in the docs.

Please or to participate in this conversation.