2017-07-15 78 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方法,其丟棄,並允許的其他部分在最初的一個之後進行測試以按預期工作。