How to make migration tests for Laravel package

If you create a Laravel Package with Eloquent Models, then you probably want to test them.

Since its nice to run the test inside the package and not require an outer Laravel Application, one should use Orchestral Testbench.

First, make sure that you have correctly registered your Service Provider and pointed with loadMigrationsFrom to your migration files as explained in the docs.

If that is done, you only need to setup yout TestCase. There are three things that have to be done:

  1. Setup a SQLite DB in memory
  2. Point to your Service Provider
  3. Run migrate in your setup method

Thats it!

Here is an actual example that I use in real life:

<?php

namespace Memberportal\CongressesModels\Tests;

use Illuminate\Contracts\Debug\ExceptionHandler;
use Memberportal\CongressesModels\CMServiceProvider;

class TestCase extends \Orchestra\Testbench\TestCase
{
    public function setUp(): void
    {
        parent::setUp();

        $this->artisan('migrate', ['--database' => 'testbench'])->run();
        $this->loadLaravelMigrations();
    }

    /**
     * add the package provider
     *
     * @param $app
     * @return array
     */
    protected function getPackageProviders($app)
    {
        return [CMServiceProvider::class];
    }

    /**
     * Define environment setup.
     *
     * @param  \Illuminate\Foundation\Application  $app
     * @return void
     */
    protected function getEnvironmentSetUp($app)
    {
        // Setup default database to use sqlite :memory:
        $app['config']->set('database.default', 'testbench');
        $app['config']->set('database.connections.testbench', [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ]);
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *