Accidentally deleting Laravel database when running tests? Here is what to do instead

·

1 min read

For a long time in my first years of dev journey I would accidentally wipe out the local database when I would run tests. This would because I have cached the config for unspecified reasons.

After falling into the same pit hole for enough times, I figured there's a way out.

So far every Laravel project comes with a phpunit.xml file. This file contains environment variables that are loaded when tests run. If they are not, that's how we can accidentally delete the database. If they're not, that's how we can also save ourselves.

In the tests/CreatesApplication.php file we need to check that we're in a testing environment, if not, we trigger a fatal error:

<?php

namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__ . '/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        if ($app->runningUnitTests() === false) {
            trigger_error('Wrong testing environment, phpunit.xml ignored');
        }

        return $app;
    }
}