0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel TestCaseのDB migration 設定

Posted at

はじめに

新しいbranchでテストを実行したところ、DBが存在しないよ!エラーに当たったのでテストケース用のDBマイグレーションの設定方法をメモ。

設定

1. TestCase.php

テストケースの基盤となるクラス。通常はtestsの下に存在します。
このクラスに、テスト環境を整えるためのsetUp関数を設定していきます。

abstract class TestCase extends BaseTestCase
{
//....
    protected function setUp(): void
    {
        parent::setUp();
        DB::beginTransaction(); // Start transaction
        $this->artisan('migrate:fresh'); // Migration
    }

    protected function tearDown(): void
    {
        DB::rollBack(); // transaction rollback
        parent::tearDown();
    }
}

この設定により、各テストの実行前にsetUpメソッドが呼び出され、データベースがリフレッシュされます。マイグレーションをテスト全体の前に一度だけ実行するか、各テスト毎に実行するかは、要件に応じて設定してください。

データベーススキーマの設定は、$this->artisan('migrate:fresh');で実行されます。この段階で必要となるマイグレーションファイルを作成します。

2. Migration file

テストに必要なテーブルuser_tableを例にマイグレーションファイルを作成します。

<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class CreateTestTables extends Migration
{

    public function up(): void
    {
        DB::unprepared('
            DROP TABLE IF EXISTS `user_table`;
            /*!40101 SET @saved_cs_client     = @@character_set_client */;
            /*!40101 SET character_set_client = utf8 */;
            CREATE TABLE `user_table` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(20) NOT NULL,
              `phone_number` varchar(15) DEFAULT NULL,
              `birthday` date DEFAULT NULL,
              `post_id` varchar(7) DEFAULT NULL,
              `delete_flg` char(1) DEFAULT '0',
              `regist_datetime` datetime DEFAULT NULL,
              `update_datetime` datetime DEFAULT NULL,
              CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        ');
    }

    public function down(): void
    {
        DB::unprepared('
            DROP TABLE IF EXISTS `user_table`;
        ');
    }
}

このマイグレーションでは、migrate:freshコマンド実行時にupメソッドが呼び出され、定義されたuser_tableが作成されます。

おわりに

実際のプロジェクトでは、up()の中身は凄まじく長い内容になる可能性があるので、別ファイルに書いてファイルを読み込むという形の方が管理しやすいかと思いまs。
参考になれば幸いです🍏

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?