gizmojo's avatar

How to run migrations in a test?

Within a package test, how would I handle the migration files that are in .php.stub format?

I want to avoid duplicating them to tests folder.

protected function defineDatabaseMigrations()
{
    $this->loadLaravelMigrations();
    $this->loadMigrationsFrom(__DIR__ . '/database/migrations');
}
0 likes
1 reply
gizmojo's avatar

I've created a test database so I can see what's going on. But I keep getting error:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table users (id bigint unsigned not null auto_increment primary key, name varchar(255) not null, email varchar(255) not null, email_verified_at timestamp null, password varchar(255) not null, remember_token varchar(100) null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:760 756▕ // If an exception occurs when attempting to run a query, we'll format the error 757▕ // message to include the bindings with SQL, which will make this exception a 758▕ // lot more helpful to the developer instead of just the database's errors. 759▕ catch (Exception $e) { ➜ 760▕ throw new QueryException( 761▕ $query, $this->prepareBindings($bindings), $e 762▕ ); 763▕ } 764▕ }

  +9 vendor frames

10 tests/database/migrations/create_users_table.php:10 Illuminate\Support\Facades\Facade::__callStatic("create")

  +31 vendor frames

42 tests/TestCase.php:87 Orchestra\Testbench\TestCase::loadMigrationsFrom("/tests/database/migrations")

Tests: 1 failed Time: 2.87s

Script vendor/bin/pest handling the test event returned with error code 2

The loadMigrationsFrom isn't recognising the config database.default for some reason and running the migrate command without database option

<?php

namespace Vendor\Package\Tests;

use BladeUI\Heroicons\BladeHeroiconsServiceProvider;
use BladeUI\Icons\BladeIconsServiceProvider;
use Vendor\Package\VendorPackageServiceProvider;
use Vendor\Package\Tests\Models\User;
use Filament\FilamentServiceProvider;
use Filament\Forms\FormsServiceProvider;
use Filament\Notifications\NotificationsServiceProvider;
use Filament\Support\SupportServiceProvider;
use Filament\Tables\TablesServiceProvider;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Livewire\LivewireServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;

class TestCase extends Orchestra
{
    use RefreshDatabase;
    use WithFaker;

    protected User $adminUser;

    protected function setUp(): void
    {
        parent::setUp();
    }

    protected function getPackageProviders($app)
    {
        $packageProviders = [
            BladeHeroiconsServiceProvider::class,
            BladeIconsServiceProvider::class,
            VendorPackageServiceProvider::class,
            FilamentServiceProvider::class,
            FormsServiceProvider::class,
            LivewireServiceProvider::class,
            LivewireServiceProvider::class,
            NotificationsServiceProvider::class,
            SupportServiceProvider::class,
            TablesServiceProvider::class,
        ];

        return $packageProviders;
    }

    public function getEnvironmentSetUp($app)
    {
        config()->set('auth.providers.users.model', User::class);
        
        config()->set('app.key', 'base64:EWcFBKBT8lKlGK8nQhTHY+wg19QlfmbhtO9Qnn3NfcA=');

        config()->set('database.connections.testbench', [
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'port' => '3306',
            'database' => 'testbench',
            'username' => 'root',
            'password' => 'mysql',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                \PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]);
        config()->set('database.default', 'testbench');
    }

    protected function defineDatabaseMigrations()
    {
        $this->loadLaravelMigrations();
        $this->loadMigrationsFrom(__DIR__ . '/database/migrations');
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
        $this->artisan('migrate', ['--database' => 'testbench'])->run();
    }
}

Please or to participate in this conversation.