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?

More than 1 year has passed since last update.

【Laravel】assertDatabaseHasで複数データを一気にテストしたい

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

状況

DBテストを書いていたら下記のエラー。
エラー文だけでググっても解決せず、少し苦労したので備忘録とする。

str_ends_with(): Argument #1 ($haystack) must be of type string, array given

複数のデータが入っているかを一気にテストしたかったため、
配列の配列を第2引数としていた。
直感的にこう書けるかなと思ったがだめっぽい。

$users = User::factory(2)->create();

$this->assertDatabaseHas('post_histories', [
   'user_id' => $users[0]->id,
   'hoge_type' => 'hoge',
], [
   'user_id' => $users[1]->id,
   'hoge_type' => 'hoge',
]);

解決法

DBテストではレコードごとにデータが入っているかをテストする。

$users = User::factory(2)->create();

$this->assertDatabaseHas('posts', [
   'user_id' => $users[0]->id,
   'title' => $params['title']
   'content' => $params['content']
]);

$this->assertDatabaseHas('posts', [
   'user_id' => $users[1]->id,
   'title' => $params['title']
   'content' => $params['content']
]);

assertDatabaseHasの実装を見てみると、配列の配列を渡せない実装になっていた!
(array $dataの部分)

protected function assertDatabaseHas($table, array $data, $connection = null)
{
   $this->assertThat(
       $table, new HasInDatabase($this->getConnection($connection), $data)
   );

   return $this;
}


class HasInDatabase extends Constraint
{
...
   public function matches($table)
   {
      return $this->database->table($table)->where($this->data)->count() > 0;
   }
...
}

参考

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?