skip to Main Content

I am wondering how to change the database in Laravel parallel test. I changed the database as below but it didn’t work.

ParallelTesting::setUpTestCase(function (int $token, TestCase $testCase) {
    $newDb = getenv("DB_DATABASE") . $token;
    Config::set('database.connections.mongodb.database', $newDb);
    app("db")->purge($newDb);
});

I have to change the database for each test so that errors and failures do not occur.

2

Answers


  1. Chosen as BEST ANSWER

    After a few hours of struggling with this problem, I finally solved it. I just changed the code above to this and it worked.

    ParallelTesting::setUpTestCase(function (int $token) {
        $dbName = getenv("DB_DATABASE") . $token;
        config(['database.connections.mongodb.database' => $dbName]);
        DB::purge('mongodb');
        DB::reconnect('mongodb');
        app()->make(PermissionRegistrar::class)->forgetCachedPermissions();
    });
    

  2. Typically, you don’t need to define configs to run parallel tests. And tests running in parallel will know how to access them.

    Therefore, all you need to do is run seeding (if you use it, or something other) when creating copies of test databases:

    class AppServiceProvider extends ServiceProvider
    {
        public function boot(): void
        {
            if ('testing' === $this->app->environment()) {
                ParallelTesting::setUpTestDatabase(function () {
                    Artisan::call('db:seed');
                    # Perhaps some other actions
                });
            }
        }
    }
    

    In composer.json you can prepare next commands in scripts

    "test-prepare": [
        "@php artisan config:clear --env=testing",
        "@php artisan route:clear --env=testing",
        "@php artisan db:wipe --env=testing",
        "@php artisan migrate:refresh --force --seed --env=testing"
    ],
    "test": [
        "@php artisan test --env=testing --parallel --processes=4 --recreate-databases"
    ],
    "test-full": [
        "@test-prepare",
        "@test"
    ]
    
    

    And run:

    composer test – when you just need to run the tests again

    composer test-full – when the table structures in the database have changed, or the first run (including CI scenario).

    composer test-prepare – when you don’t want to run parallel tests, but you need to update the main test db after changes (and than run tests manually).

    Enjoy it

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search