1
0

More than 1 year has passed since last update.

【PHPUnit】Factoryのstateを使ってテストデータを作成する

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

前置き

テストデータの一部を変更して使いたいとき、下記のように書くこともできるが
RSpecで使われるFactoryBotのtraitのように便利に書けるものがないか調べたらあった。

Task::factory()->create([
  'status' => 'done',
]);

Factoryのstate

ファクトリの状態を一部変更してテストデータを作成できる。
Laravel8から使える。

class TaskFactory extends Factory
{
  ...
  public function done(): TaskFactory
  {
    return $this->state(function (array $attributes) {
      return [
        'status' => 'done',
      ];
    });
  }
}

テスト内で下記のように定義して使える。

Task::factory()->done()->create();

参考

1
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
1
0