Summer Sale! All accounts are 50% off this week.

jrdavidson's avatar

Pest Testing Against Collection

Does anyone know what would be the best way to test a model relationship collection? Below I am testing that new players can be added to a team through an update request for the team. What I'm wanting to test at the end of the test is that players includes all players (both former and new).

toContain must be a full array of all included values.

$formerPlayers = Player::factory()->count(2)->create();
$team = Team::factory()
    ->hasAttached($formerPlayers, ['joined_at' => now()->toDateTimeString()])
    ->create();
$newPlayers = Player::factory()->count(2)->create();

// PATCH REQUEST HERE

expect($team->fresh())
    ->players->toHaveCount(4)->toContain($newPlayers)
0 likes
2 replies
martinbean's avatar

@jrdavidson Your $formerPlayers and $newPlayers variables are collection instances, so you could merge them to check all are attached to the team after your PATCH request:

$expectedPlayers = $formerPlayers->merge($newPlayers);

// Iterate over $expectedPlayers here and assert they're attached to team
1 like
jrdavidson's avatar

@martinbean Maybe I'm missing something here. I'm trying to make sure that the ids of the players relationship collection match the collection of all player ids match.

$formerPlayers = Player::factory()->count(2)->create();
$team = Team::factory()
    ->hasAttached($formerPlayers, ['joined_at' => now()->toDateTimeString()])
    ->create();
$newPlayers = Player::factory()->count(2)->create();

/ PATCH REQUEST HERE

$allPlayers = $formerPlayers->merge($newPlayers);

expect($team->fresh())
    ->players->toHaveCount(4)->toContain($newPlayers)

Please or to participate in this conversation.