Jon Winstanley
Jon Winstanley

Reputation: 23311

Testing multiple databases in Laravel with phpunit

In my application I have tests that use Sqlite and seeding to cover my functionality. So my phpunit env value is set to:

<env name="DB_DEFAULT" value="sqlite" />

However, I'd also like a small subset of my tests to look at my current db data. So within 1 test file, connect to my MySQL connection.

The reason for this is I want to check if we have images for all the records in one of my tables, so the test needs to access the latest data, dummy data would not help in this case.

I presumed I could just connect using the following:

$pdo = DB::connection('mysql')->getPdo();

However, the test only connects if I specify "sqlite" here, which is the name of my sqlite connection.

The testing I want to do is not based on a Model, so I don't want to have a solution built into my Model file, I'd like to switch database just in this 1 test file if possible.

How do I configure a small number of tests to use a different database connection, the existing MySQL connection?

Upvotes: 1

Views: 1232

Answers (1)

Jon Winstanley
Jon Winstanley

Reputation: 23311

So, the reason why I could not connect was because there were no DB_ values in my .env.testing file. The mysql connection was then using the Laravel config defaults so the connection did not error.

.env.testing

DB_DEFAULT=mysql
DB_HOST=database
DB_NAME=my_database_name
DB_USER=root
DB_PASS=root

Adding the lines above got everything working and now my test file can access the current local database.

public function __construct()
{
    $this->imgPath = dirname(__FILE__, 3) . '/public/images/';
}

public function testImages()
{
    $items = DB::connection('mysql')
        ->select(DB::raw('SELECT image_filename FROM items')
    );

    foreach ($items as $item) {
        $this->assertFileExists($this->imgPath . $item->image_filename . '.jpg');
    }
}

Upvotes: 1

Related Questions