Laravel 11
Since Laravel 11 removed `tests/CreatesApplication.php` file I had to dig up a new solution. Sadly, there isn't the perfect pretty one. I had to overwrite the refreshApplication method which comes from the BaseTestCase class.
protected function refreshApplication(): void
{
parent::refreshApplication();
if ($this->app->runningUnitTests() === false) {
trigger_error('Wrong testing environment, phpunit.xml ignored');
}
}
Before Laravel 11 (original write up)
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
{
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;
}
}