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

GJV's avatar
Level 1

Multiple Database Connection - Repository Integration Testing

Im doing a database integration / functional testing for a repository class. I am now testing an update function that uses a model that has a defined db connection, which is different from the default db connection. How can I transact and rollback from the model's db connection? I have tried this one: https://github.com/laravel/framework/issues/10873#issuecomment-289348849 I have also tried this one: https://laracasts.com/discuss/channels/laravel/transactions-with-multiple-database-connections But they both have the same result, the data won't be updated.

0 likes
2 replies
tisuchi's avatar

@gjv How about this?

    public function testUpdate()
    {
        // Connect to the desired database connection
        $connection = DB::connection('my_connection');
        $connection->beginTransaction();

        // Do the update

        // Check if the update was successful

        // Rollback the transaction
        $connection->rollBack();
    }
azimidev's avatar
try {
    DB::connection($model->getConnection()->getName())->beginTransaction();
    $model->update([...]);
    DB::connection($model->getConnection()->getName())->commit();
} catch (\Exception $e) {
    DB::connection($model->getConnection()->getName())->rollBack();
    throw $e;
}

should be inside a try-catch block to ensure that the transaction is rolled back in case of any exceptions.

Please or to participate in this conversation.