Skip to main content

Testing Side Effects with Laravel Fakes

Premium
4 min read

Some actions in your application do more than return a response — they send emails, push jobs to a queue, write files, or call external APIs. How do you test that those things would happen, without actually sending an email or writing a file every time you run your test suite?

Laravel has a built-in answer: fakes.


The Problem with Side Effects

Side effects make tests slow and brittle. If your test actually sends an email, it depends on a working mail server. If it writes to S3, it needs valid credentials. If it calls an external API, it can fail when the service is down.

Fakes replace the real implementation with a silent in-memory version for the duration of the test. You call ::fake() before the action, run the action, then assert that the expected interaction happened.


Mail::fake()

Call Mail::fake() before the action that triggers an email. Laravel will intercept the mailable and record it instead of sending it.

tests/Feature/OrdersTest.php:

use Illuminate\Support\Facades\Mail;
use App\Mail\OrderConfirmation;
 
test('order confirmation email is sent after checkout', function () {
Mail::fake();
 
$user = User::factory()->create();
$order = Order::factory()->create(['user_id' => $user->id]);
 
actingAs($user)
->post('/checkout', ['order_id' => $order->id])
->assertRedirect('/orders');
 
Mail::assertSent(OrderConfirmation::class);
});

You can also assert the recipient:

Mail::assertSent(OrderConfirmation::class, function ($mail) use ($user) {
return $mail->hasTo($user->email);
});

And assert nothing was sent when you expect it not to be:

Mail::assertNothingSent();

Notification::fake()

Works the same way as...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (34 h 11 min)

You also get:

58 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.