Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Handle multiple connections and testing

I have a Laravel 5.4 app which has models pointing to different database connections.

For example, I have User pointing to a MySQL database and then Company pointing to a PostgreSQL database (using the $connection variable).

Now, when I run PHPUnit I'd like the $connection variable to be replaced by what's specified in the phpunit.xml file, which is a SQLite in memory type of database.

How is that achievable?

like image 798
Felipe Peña Avatar asked Apr 18 '17 14:04

Felipe Peña


2 Answers

As mentioned before, you first need to set the connection in each Model. So, you setup the connections in the database config file, set the values in the .env file and use these in the Model's constructors.

For testing, you could also do this. Add the testing connection to the config/database.php file and then use an overriding env file.

Create an additional env file, name it something like .env.testing.

So, in your .env file you will have:

CONNECTION_MYSQL=mysql
CONNECTION_POSTGRESS=postgress

Then in the .env.testing file you can have:

CONNECTION_MYSQL=test_sqlite
CONNECTION_POSTGRESS=test_sqlite

Finally to load this env file when testing, go to CreatesApplication trait and update to the following:

public function createApplication()
{
    $app = require __DIR__.'/../bootstrap/app.php';

    $app->loadEnvironmentFrom('.env.testing');

    $app->make(Kernel::class)->bootstrap();

    return $app;
}

By using the loadEnvironemtFrom() method, all tests that use this trait will load the .env.testing file and use the connections defined there.

like image 72
achillesp Avatar answered Nov 16 '22 02:11

achillesp


Most answers are changing production code, which I don't like.

Since \Illuminate\Contracts\Foundation\Application is available in your tests, let's use it!

<?php

declare(strict_types=1);

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\Company;    

class CompanyFeatureTest extends TestCase
{
    /**
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();

        $this->app->bind(Company::class, function () {
            return (new Company())->setConnection(config('database.default'));
        });
    }
}

Whenever your Company class is called, we give back a manipulated one.
In this one we have changed the $connection property.

If you have the following in your phpunit.xml:

<server name="DB_CONNECTION" value="sqlite"/>

The value of config('database.default') will be sqlite.

More info about binding can be found here: https://laravel.com/docs/5.8/container#binding

like image 39
Ron van der Heijden Avatar answered Nov 16 '22 02:11

Ron van der Heijden