G
G
ganjo8882020-04-14 14:31:49
PHP
ganjo888, 2020-04-14 14:31:49

How to switch db connections during phpunit tests?

The application uses two databases pqsql and mongo. Framework - laravel.
In my test, I use factories to create an entry in mongodb. How can I make it so that the entry is created in the test database, namely mongodb_test ? How can I switch between test databases?

This is how I create a test entry in the
factory(TestModel::class)->create();

TestModel database

class TestModel extends Eloquent
{
    use SnakeCaseToCamelCaseTrait, BelongsToModelJoin;
    public $connection = 'mongodb';
    protected $collection = 'test';
}

For tests created such configs.
'pgsql_test' => [
            'driver'   => 'pgsql',
            'host'     => env('POSTGRES_HOST', '127.0.0.1'),
            'port'     => env('POSTGRES_PORT', '5432'),
            'database' => env('DB_TEST_DATABASE', 'forge'),
            'username' => env('POSTGRES_USER', 'forge'),
            'password' => env('POSTGRES_PASSWORD', ''),
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
            'sslmode'  => 'prefer',
        ],
        'mongodb_test' => [
            'driver'   => 'mongodb',
            'host'     => env('MONGO_HOST', 'localhost'),
            'port'     => env('MONGO_PORT', '27017'),
            'database' => env('DB_TEST_DATABASE', 'laravel'),
            'username' => env('MONGO_USERNAME', ''),
            'password' => env('MONGO_PASSWORD', ''),
            'options'  => [
                'database' => 'admin',
            ],
        ],

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question