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

charlieBrown's avatar

AssertTrue PHP Unit [Laravel 5.1]

I'm a beginner in the area of testing and I would like to know why is this not working:

public function testUserDoesntGetDuplicatedKey()
    {
        $this->withoutMiddleware();

        \App\User::truncate();
        $users = factory(\App\User::class, 10)->create()->each(function ($user){
            $user->country()->save(factory(\App\UsersCountry::class)->create());
        });

        foreach($users as $user){
            $this->actingAs($user)
                ->visit('giveaway/1b29f33b-4387-32c3-acab-d9e023de4d4c')
                ->click('btnGetKeyTesting');
        }

        dd(\App\UserKeys::count());

        $this->assertTrue(\App\UserKeys::count() == 10);
    }

The steps that I'm trying to reproduce is:

1 - User gets to the page giveaway/1b29f33b-4387-32c3-acab-d9e023de4d4c
2 - Click the button "btnGetKeyTesting"
3 - A call is made to /ajax/keyManagement/getKeyGiveaway
4 - In this call the following happens
4.1 - Get the key 
4.2 - Insert into table users_keys the key and the user who got the key

When I make the dd(\App\UserKeys::count()) it returns 0 which should return 10 since I'm creating 10 users. What is missing to me here?

0 likes
2 replies
Cronix's avatar

You might try putting a slight delay in your foreach($users) loop. sleep(1) or something.

I think your

->visit('giveaway/1b29f33b-4387-32c3-acab-d9e023de4d4c')

also needs to have a beginning /, like /giveaway/uuid. Not sure if that matters, but that's what the examples in the docs show.

1 like
charlieBrown's avatar
charlieBrown
OP
Best Answer
Level 2

Than you @Cronix for your answer.

After reading more carefully the docummentation I found post which resulted in:

$this->actingAs($user)
                ->post('ajax/keyManagement/getKeyGiveaway', ['giveawayID' => '1b29f33b-4387-32c3-acab-d9e023de4d4c']);

Since my objective here (which I wasnt very clear) is to make the request to that route this is the appropriate method for me.

Once again, thank you for your answer. Have a great day

Please or to participate in this conversation.