6
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?

More than 3 years have passed since last update.

[Laravel] テスト実行時にテストデータがDBに残らないようにする方法

Posted at

laravelでテストを実行したときに、テストデータがDBに残らないようにしたい。
そんな時に便利なのが、LaravelのDatabaseTransactionsトレイトです。

DatabaseTransactionsの使い方

ServiceTest.php
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ServiceTest extends \TestCase
{
    use DatabaseTransactions;
    public function setUp():void
    {
      //

テストのソースに上記のuse文を3つ追加するだけです。

DatabaseTransactionsで行われていること

DatabaseTransactionsを利用すると
テストを実行しているあいだだけ有効なトランザクションを作ってくれます。
つまり、テストのsetup時点でbeginTransactionして、テスト終了時にrollbackしてくれます。

注意点

autoIncrementのカラムで、自動採番された数字は戻らないです。
例) users.id=1のレコードがrollbackされても、レコードは消えるが、次採番されるidは2になる。

参考文献

[データベースのテスト 5.4 Laravel - ReaDouble]
(https://readouble.com/laravel/5.4/ja/database-testing.html)
LaravelでRefreshDatabaseを使えない場合はどうするべきか

6
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
6
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?