2017-07-15 56 views
0

我想用Laravel运行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) 

我尝试了一些代码,我的互联网,它使用的测试类,这对于第一次测试工作正常的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 = '[email protected]'; 
    $this->user->password = ''; 
    $this->user->save(); 
} 

,甚至试图加入migrate:rollback呼叫测试的方法tearDown,不得要领:

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

有关如何解决此问题的任何想法?

回答

1

所以刚发布这个问题后,我看着迁移,因为我意识到在我的user_roles表之前有一些表正在迁移。就在这个时候,我注意到,down功能移除了表的外键,但并没有放弃它:每次测试后

/** 
* 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方法,其丢弃,并允许的其他部分在最初的一个之后进行测试以按预期工作。