Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jeFFF's avatar
Level 3

Does Pest as trouble with 'sync' functions

Hello all,

I have s strange issue with pest. I've got an action class which sync roles like this :

$etude->allRoles()->sync($roles);

In a pest test, I tried to test if roles are set with this :

$etude = Etude::factory()->withChefDeProjet()->make()->toArray();
    actingAs($this->super_admin, 'backpack')
        ->post(route('etude.store'), $etude)
        ->assertRedirect(route('etude.index'));
    $etudeCreated = Etude::with('allRoles')->latest()->first();
    expect($etudeCreated->allRoles->count())->toBe(1);

The trouble is, sometimes the test pass and sometimes not. I put a 'dd' in the action, and each time, the data are always set correcly so I assumed pest was acting to quickly and did not wait the sync function to occur.

Did someone has these kind of problems, or more simply, did I do something wrong ? Thanks for your help

0 likes
1 reply
LaryAI's avatar
Level 58

It looks like you are running into an issue with the synchronization not completing before the test is finished. You can try using the refresh() method on the $etudeCreated object before running the assertion. This will force the object to reload from the database and should ensure that the synchronization has completed.

$etudeCreated->refresh();
expect($etudeCreated->allRoles->count())->toBe(1);

Please or to participate in this conversation.