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のユニットテストで気を付けること

Posted at

.env.testing にテスト用DB情報、.env にローカル用DB環境を設定し、
php artisan config:cache を実行すると、.envの内容がキャッシュされ(bootstrap/cache/config.php 化され)それが最優先になる。

つまり、php artisan test を実行すると、.env.testingを見ずに、キャッシュされた .env(bootstrap/cache/config.php)のほうをみてしまう。(試したら実際そうだった)

そうすると、php artisan test を実行すると、ローカル環境のDBに対してテストを実施してしまう。

とくに use RefreshDatabase;なんか使ってたときには、ローカル環境のDBをDropしてマイグレーションし直してしまう

さらに怖いことには、本番環境で php artisan test なんかしたときには、本番DBを消し飛ばしてしまう可能性も。

本番環境では php artisan test コマンドを実行しない事が大切と言われますが、人間なのでやらかしかねないので、test/TestCase.php に以下のコードを記載しました。

これで、APP_ENV が testing 以外ならばテストが実行されなくなります。

tests/TestCase.php
<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    protected function setUp(): void
    { 
        parent::setUp();

        if (!app()->environment('testing')) {
            exit("テスト環境以外でテストを実行しようとしています。中止します。\n");
        }
    }
}
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?