Summer Sale! All accounts are 50% off this week.

zoidq's avatar
Level 7

Tests ignoring .env.testing

Hey folks,

After upgrading to Laravel 10, I'm having the following problem:

php artisan test

Results in all my tests failing since they are using the wrong env vars for the database:

SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO) (Connection: mysql, SQL: select * from information_schema.tables where table_schema = :memory: and table_name = migrations and table_type = 'BASE TABLE')

My .env.testing config is configured correctly and phpunit.xml contains the following:

<env name="APP_ENV" value="testing"/>

The only way I can get the tests to use the env file is to cache the config like so:

php artisan config:cache

INFO  Configuration cached successfully.

Then all tests work correctly. Any idea why artisan is ignoring my testing environment file and only working when config is cached?

Thanks in advance.

0 likes
2 replies
LaryAI's avatar
Level 58

It's possible that your .env.testing file is not being loaded properly. Try running php artisan config:clear to clear the configuration cache and then run your tests again. If that doesn't work, try explicitly specifying the environment file when running your tests:

php artisan test --env=testing

If that still doesn't work, you can try manually loading the environment file in your tests by adding the following code to the top of your test file:

use Illuminate\Foundation\Testing\RefreshDatabase;

class MyTest extends TestCase
{
    use RefreshDatabase;

    public function setUp(): void
    {
        parent::setUp();

        $this->loadEnvironmentVariables();
    }

    // ...
}

This will load the environment variables from your .env.testing file before running your tests.

1 like
zoidq's avatar
Level 7

This was resolved by addressing a upgrade step that had been missed:

Furthermore, if you wish to use PHPUnit 10, you should delete the processUncoveredFiles attribute from the <coverage> section of your application's phpunit.xml configuration file. Then, update the following dependencies in your application's composer.json file:

nunomaduro/collision to ^7.0
phpunit/phpunit to ^10.0
1 like

Please or to participate in this conversation.