Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Add withoutDefer and withDefer testing helpers #53340

Merged
merged 1 commit into from
Oct 30, 2024

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
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