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

1stevengrant's avatar

Seeding my database from sql while testing

Trying to make the move to Pest for our test suite.

Have a simple test right now that fails because the table testing.videos doesn't exist.

test('home page loads without error', function (): void {
    $this->get('/')->assertOk();
});

the underlying test case looks like so

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
}

and then before each test I'm doing

beforeEach(function () {
    $this->withoutExceptionHandling();
    $this->artisan('db:seed --class=DatabaseSeeder');
});

DatabaseSeeder is a seeder that runs

$file = database_path('seeders/_db-dump.sql');
$sql = File::get($file);
DB::connection()->getPdo()->exec($sql);

The videos table definitely exists in the sql extract, so why is it choking? I even attempted to move the before each into setUp in the TestCase but still with the same error.

Am I missing something really obvious?

0 likes
1 reply
illuminatixs's avatar

Hey there,

Starting with Laravel 8 the trait: RefreshDatabase can look for a class var: "seed" . if you add: protected $seed = true; as a class variable, it will trigger the migration + the seeder.

This is what it would look like in your example case:

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication, RefreshDatabase;

	protected $seed = true;

	// Your tests here.
}

But on to your main question, Why isn't this working!?:

If I purely look at your given code, the “migrate” functionality isn't triggered, and PHPUnit might be connected to a different database connection than the one you would expect. Check the phpunit.xml file if the property: DB_CONNECTION is set to anything other than what your main application uses.

It is a bit of a stretch, but all I can find with the limited information.

Hope this helps.

Please or to participate in this conversation.