Skip to content

[11.x] Make mailables tappable#53788

Merged
taylorotwell merged 1 commit into
laravel:11.xfrom
kevinb1989:make-mailables-tappable
Dec 8, 2024
Merged

[11.x] Make mailables tappable#53788
taylorotwell merged 1 commit into
laravel:11.xfrom
kevinb1989:make-mailables-tappable

Conversation

@kevinb1989

@kevinb1989 kevinb1989 commented Dec 7, 2024

Copy link
Copy Markdown
Contributor

I have been enjoying using the tap method from the Illuminate\Testing\TestResponse class, when I got a little logics around assertions.

The Illuminate\Mail\Mailable class contains assertion methods. It would be nice to also make it tappable.

I have the following real-life example from my organization:

use App\Mails\OrderCompleted;
use App\Models\Customer;
use App\Models\Order;

public function test_emails_containing_correct_addresses(country $countryCode)
{
    $order = Order::factory()
        ->for(Customer::factory()->create(['country' => $countryCode]))
        ->create();

    $mail = new OrderCompleted($order);

    $mail->assertHasSubject('Your Order Has Been Fulfilled!');

    match (true) {
        $countryCode === 'AU' => $mail->assertSeeInHtml('64 Barker Street REDMOND WA 6327'),
        $countryCode === 'US' => $mail->assertSeeInHtml('2142 Doctors Drive, Burbank, CA 91505'),
        $order->customer->is_from_europe => $mail->assertSeeInHtml('Gerrit van der Veenstraat 1 1077 DX  Amsterdam'),
    };
}

As a global business, we want to display correct branch address in our emails depending on the customer's location.

I would prefer to do all assertions in one go:

$mail->assertHasSubject('Your Order Has Been Fulfilled!')
    ->tap(function ($mailable) use ($countryCode, $order) {
        match (true) {
            $countryCode === 'AU' => $mailable->assertSeeInHtml('64 Barker Street REDMOND WA 6327'),
            $countryCode === 'US' => $mailable->assertSeeInHtml('2142 Doctors Drive, Burbank, CA 91505'),
            $order->customer->is_from_europe => $mailable->assertSeeInHtml('Gerrit van der Veenstraat 1 1077 DX Amsterdam'),
        };
    });

@taylorotwell taylorotwell merged commit 36b09b7 into laravel:11.x Dec 8, 2024
browner12 pushed a commit to browner12/framework that referenced this pull request Dec 10, 2024
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.

2 participants