Laravel 测试数据库不回滚

Laravel Tests Database Doesn't Roll Back

我正在尝试 运行 CI 测试 Laravel。然而,测试总是失败,因为数据库似乎并没有在每次测试后回滚。这会导致如下错误:

Illuminate\Database\QueryException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'user_roles' already exists (SQL: create table `user_roles` (`id` int unsigned not null auto_increment primary key, `user_id` int unsigned not null, `role_id` int unsigned not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

我尝试了一些我在互联网上找到的代码,它在测试 class 中使用了 DatabaseMigrations 特性,它在第一次测试中运行良好,但在其余测试中不起作用他们:

/**
* Set up the environment for testing.
*/
public function setUp()
{
    parent::setUp();
    $this->runDatabaseMigrations();

    // Create an example user
    $this->user = new User();
    $this->user->name = 'Test User';
    $this->user->email = 'test@example.com';
    $this->user->password = '';
    $this->user->save();
}

甚至尝试添加对测试的 tearDown 方法的 migrate:rollback 调用,但无济于事:

public function tearDown()
{
    parent::tearDown();
    $this->artisan('migrate:rollback');
}

关于如何解决这个问题有什么想法吗?

所以在发布这个问题之后,我查看了迁移,因为我意识到在我的 user_roles table 之前有几个 table 正在迁移。这是我注意到 down 函数从 table 中删除外键但没有删除它的时候:

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('user_roles', function (Blueprint $table) {
        $table->dropForeign('user_roles_user_id_foreign');
        $table->dropForeign('user_roles_role_id_foreign');
    });
}

Schema::drop('user_roles'); 添加到 down 方法,在每次测试后将其删除,并允许初始测试后的其余测试按预期运行。