1

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?

1 Answer 1

1

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');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.