Skip to content

Instantly share code, notes, and snippets.

@HighLiuk
Last active July 11, 2022 08:24
Show Gist options
  • Save HighLiuk/debf2da9d39bbc8f8d8268e540eb9c4c to your computer and use it in GitHub Desktop.
Save HighLiuk/debf2da9d39bbc8f8d8268e540eb9c4c to your computer and use it in GitHub Desktop.
Laravel - Refresh Database Once
<?php
namespace Tests;
use Illuminate\Foundation\Testing\Traits\CanConfigureMigrationCommands;
/**
* Refreshes the database once.
*
* This is inspired by a post of Stefan Dreßler at medium.com
*
* @see https://medium.com/helpspace/fresh-database-once-befor-testing-starts-faa2b10dc76f
*/
trait RefreshDatabaseOnce
{
use CanConfigureMigrationCommands;
/**
* If true, setup has run at least once.
*
* @var boolean
*/
protected static $setUp_has_run_once = false;
/**
* Refreshes the database once.
*
* Use it in your setUp function
*
* @return void
*/
public function refreshDatabaseOnce()
{
if (static::$setUp_has_run_once) {
return;
}
$this->artisan('migrate:fresh', $this->migrateFreshUsing());
static::$setUp_has_run_once = true;
}
}
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
use RefreshDatabaseOnce;
/**
* Setup the test environment.
*
* @return void
*/
protected function setUp(): void
{
parent::setUp();
$this->refreshDatabaseOnce();
// extra method calls
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment