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

definition に書くべき項目

1
Posted at

definition() は「そのモデルの デフォルト状態」を返します。

phppublic function definition(): array
{
    return [
        'name' => fake()->name(),              // NOT NULL なら必須
        'email' => fake()->unique()->safeEmail(),
        // 'tel' => ...   // NULL許可なら必須ではない
    ];
}
  • NOT NULL かつ DB にデフォルト値がないカラム

    → factory 側で必ず値を返すようにしておく(最低限ここは埋める)。

  • NULL 許可のカラム(nullable)

    → definition() に書かなくてもよい。必要なときだけ create([...]) 側で明示的に渡す。

  • デフォルト値が DB に定義されているカラム

    → factory で無理に書かなくてもよい(DB が埋めてくれる)。

「最小限だけ書いて、テスト側で上書き」が基本

factory の値は、create()make() に渡した配列で上書きできます。

// definition のデフォルトをベースに、一部だけ上書き
User::factory()->create([
    'name' => 'テスト太郎',   // ここだけ差し替え
]);

なので、

  • factory: 「ふつうのケース」の値(NOT NULL で使い回すもの)だけを定義
  • 各テスト: そのテストで必要な項目だけを 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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?