When you test code that makes an outgoing API call, Http::fake and Http::assertSent are a great combination.
You set up the fake, run the code, and then verify the request was sent with the expected payload.
Today I want to highlight a subtle gap this approach misses, and how to easily increase your test confidence.
As the docs state, Http::assertSent only checks that at least one matching request was sent.
But what if your code accidentally fires the exact same request twice? The assertion would still pass, hiding a potentially nasty bug.
The fix is simple, though. We just add one additional assertion for the request count:
Http::fake();
// call the code that will make the request here
Http::assertSentCount(1);
Http::assertSent(function (Request $request) {
// specific request and payload assertions here...
});
Now your test verifies both the content and the count. If a future code change accidentally triggers a second request, this test will catch it.
I use this same approach with events, notifications, and jobs too. For all of these faked actions, knowing how many times it happens is important to confirm.
Here to help,
Joel
P.S. Want to level up your Laravel testing skills? Our workshop covers patterns like this and a whole lot more. Check out our testing workshop.