Laravel Tutorials

Test Deferred Operations Easily with Laravel's withoutDefer Helper

Published
Test Deferred Operations Easily with Laravel's withoutDefer Helper image

Laravel introduces new test helpers to control deferred operation execution, allowing developers to test deferred functions without waiting for the request lifecycle to complete.

Control deferred execution in your tests:

// triggered deferred operations won't execute immediately
Product::create(['name' => 'Widget']);
$this->assertAgainstSomeDeferredOutcome(); // ❌ Fails

// triggered deferred operations execute immediately
$this->withoutDefer();
Product::create(['name' => 'Widget']);
$this->assertAgainstSomeDeferredOutcome(); // ✅ Passes

Here's how you might use it in your test suite:

class OrderProcessingTest extends TestCase
{
    public function test_confirmation_email_is_queued_after_order()
    {
        Mail::fake();
        
        $this->withoutDefer();

        $order = Order::create([
            'customer_id' => 123,
            'total' => 99.99,
            'status' => 'pending'
        ]);

        Mail::assertQueued(OrderConfirmationEmail::class, function ($mail) use ($order) {
            return $mail->hasTo($order->customer->email);
        });
    }

    public function test_inventory_tracking_is_updated()
    {
        Event::fake();

        $this->withoutDefer();

        $product = Product::factory()->create();
        $product->adjustStock(-5);

        Event::assertDispatched(InventoryAdjusted::class, function ($event) use ($product) {
            return $event->product_id === $product->id;
        });

        $this->withDefer();
    }
}

These helpers make it straightforward to test code that relies on deferred execution without waiting for the end of the request lifecycle.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Session Replay for Laravel: Self-Hosted Browser Recordings image

Session Replay for Laravel: Self-Hosted Browser Recordings

Read article
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article