You could also activate foreign keys on a per test (file) basis, when the tests actually depend on tables with foreign keys.
Here's a trait: (e.g. tests/ForeignKeys.php
)
<?php
namespace Tests;
trait ForeignKeys
{
/**
* Enables foreign keys.
*
* @return void
*/
public function enableForeignKeys()
{
$db = app()->make('db');
$db->getSchemaBuilder()->enableForeignKeyConstraints();
}
}
don't forget to run the method somewhere in your test set-up chain. I added mine as an override to my TestCase: (tests/TestCase.php
)
<?php
namespace Tests;
/**
* Class TestCase
* @package Tests
* @mixin \PHPUnit\Framework\TestCase
*/
abstract class TestCase extends \Illuminate\Foundation\Testing\TestCase
{
use CreatesApplication;
...
/**
* Boot the testing helper traits.
*
* @return array
*/
protected function setUpTraits()
{
$uses = parent::setUpTraits();
if (isset($uses[ForeignKeys::class])) {
/* @var $this TestCase|ForeignKeys */
$this->enableForeignKeys();
}
}
...
after that you can add it to your tests like so:
<?php
namespace Tests\Feature;
use Tests\ForeignKeys;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleFeatureTest extends TestCase
{
use DatabaseMigrations;
use ForeignKeys;
...