LoginSignup
1
1

More than 5 years have passed since last update.

Fakerで文章つくったらハマったよ

Last updated at Posted at 2016-11-15

はじめに

laravelを使っています。
テストのファクトリーを作成する際、Fakerつかいます。
そこでハマったので覚書

ハマった点

$factory->define(Post::class, function(Faker\Generator $faker) {
    return [
        'user_id' => factory(User::class)->create()->id,
        'comment' => $faker->sentences(),
    ];
});

こんな感じでファクトリーの定義をするとします。
このファクトリーをテストで使用したところ

ErrorException: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

というエラーが出てテストが通りません。

なぜ!なぜ!なぜ!!!!

と調べまくったところ、

$faker->sentences()はデフォルトでは配列を返してくるそうです。:point_down_tone2:
(これはparagraphsだけど。)
https://laracasts.com/discuss/channels/laravel/error-in-project-flyer-episode-7-preg-replace-parameter-mismatch
FakerのREAD MEにも書いてあったけどよく見てませんでした・・

解決

'comment' => $faker->sentences(),

としていたところを

'comment' => $faker->sentences(3, true),

としたらすぐ解決しました。

教訓

いつものことながら
ドキュメントはよく読みましょう:angel:

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