Laravel package testing: running framework migrations when using RefreshDatabase.
P粉955063662
2023-07-30 13:20:53
<p>I have a Laravel package that added a field to the default users table (that comes with Laravel) using migrations: </p>
<pre class="brush:php;toolbar:false;">public function up() : void
{
Schema::table('users', function (Blueprint $table) {
$table->enum('role', ['super-admin', 'admin', 'tipster', 'user'])->default('user');
});
}
</pre>
<p>When I want to run my unit tests, this causes my tests to fail because in my package, the default users table does not exist. </p><p>Is there a way to run the migrations provided by the framework when using this trait? I've used a workaround to fix this, but I really don't want to modify the code just for unit testing. </p><p><br /></p>
<pre class="brush:php;toolbar:false;">public function up() : void
{
if (App::runningUnitTests())
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->enum('role', ['super-admin', 'admin', 'tipster', 'user'])->default('user');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
else
{
Schema::table('users', function (Blueprint $table) {
$table->enum('role', ['super-admin', 'admin', 'tipster', 'user'])->default('user');
});
}
}<span style="font-family:'sans serif, tahoma, verdana, helvetica';"><span style="white-space:nowrap;"> </span></span> </pre>
<p><br /></p>
It turns out that the developers of Orchestra Testbench also took this into consideration. You can call a method to include the migration files provided by Laravel.
/** * The migrations to run prior to testing. * * @return void */ protected function defineDatabaseMigrations() : void { $this->loadLaravelMigrations(); }