Skip to content

Conversation

@timacdonald
Copy link
Member

Adds the ability to have deferred functions execute immediately within a test.

This is useful when you are working with unit tests that cover and assert against deferred function outcomes, as deferred functions are only invoked at the end of the request lifecycle.

User::create(/* ... */);

$this->assertAgainstSomeDeferredOutcome(); // will not work
$this->withoutDefer();

User::create(/* ... */);

$this->assertAgainstSomeDeferredOutcome(); // will now work

@timacdonald
Copy link
Member Author

Docs: laravel/docs#10006

@Sairahcaz
Copy link

Sairahcaz commented Oct 30, 2024

Maybe it would be nice to have a little helper for that:

function assertAfterDefer(Closure $callback): void
{
    app(DeferredCallbackCollection::class)->invoke();

    $callback();
}

it('sends an api request if a new user gets created', function () {
    User::create([
        'email' => $this->faker->safeEmail(),
        'password' => bcrypt('password'),
    ]);

    assertAfterDefer(fn () => Http::assertSent(function ($request) {
        return $request->url() == $this->apiUrl.'stats-user' && $request->method() == 'POST';
    }));
});

@taylorotwell taylorotwell merged commit fa1f4ca into laravel:11.x Oct 30, 2024
33 checks passed
@timacdonald timacdonald deleted the defer-testing-helpers branch October 30, 2024 21:40
onlime added a commit to onlime/laravel-sql-reporter that referenced this pull request Apr 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants