Laravel feature and unit tests, with a real app · Part 4 of 6
Fakes and time
A signed payment webhook, a queued receipt, a job that renders a PDF and mails it, exchange rates over HTTP and a scheduled reminder command, tested with Laravel's Mail, Bus, Event, Storage, Http and Notification fakes and a controlled clock.
By Abhishek Fouzdar · Updated
This part connects InvoiceMini to the world outside the request: a payment provider's webhook, a queue, mail, a PDF on disk, an HTTP API and a scheduled command. None of those can be real in a test, and Laravel's fakes are how a test stands in for each one. By the end there are 112 tests, still under three seconds. Part 3 built the flows; the series introduction explains InvoiceMini.
The idea behind every fake
Mail::fake(), Bus::fake(), Event::fake(), Storage::fake(), Http::fake() and Notification::fake() all do the same thing: swap the real service behind a facade for one that records what was asked of it and does nothing. The test then asserts on the record. The application code does not change and does not know. This is the whole trick, and the rest of this part is the details of each.
A fake is per test; it is installed when you call it and gone when the test ends. Call it before the code that would use the service, and after it assert with the fake's own methods, which are named assertSent, assertDispatched, assertExists and so on according to the service.
A webhook you cannot receive
When a client pays, the provider posts an event to /webhooks/payments. The body is JSON, the request carries an HMAC of the raw body in a header, and the provider will retry the same event if it does not get a 200. That gives the endpoint four jobs: verify the signature, record the payment once however many times the event arrives, mark the invoice paid when the payments cover the total, and send a receipt.
The signature is a middleware, and the two rules in it are the ones people get wrong:
public function handle(Request $request, Closure $next): Response
{
$secret = (string) config('services.paygate.webhook_secret');
$signature = (string) $request->header('X-Paygate-Signature', '');
if ($secret === '' || $signature === '') {
abort(403, 'Missing webhook signature.');
}
if (! hash_equals(hash_hmac('sha256', $request->getContent(), $secret), $signature)) {
abort(403, 'Invalid webhook signature.');
}
return $next($request);
}
Verify the raw body, $request->getContent(), never a re-encoded array, because json_encode of the decoded body is not byte-for-byte what the provider signed. Compare with hash_equals(), which takes the same time whether the first or the last byte differs. The route is excluded from CSRF in bootstrap/app.php with validateCsrfTokens(except: ['webhooks/*']); the signature is the authentication. The secret comes from phpunit.xml, PAYGATE_WEBHOOK_SECRET=test-webhook-secret, so the test can sign the way the provider does:
function postWebhook(array $payload, ?string $secret = null): TestResponse
{
$body = json_encode($payload);
$signature = hash_hmac('sha256', $body, $secret ?? config('services.paygate.webhook_secret'));
return test()->call('POST', '/webhooks/payments', [], [], [], [
'CONTENT_TYPE' => 'application/json',
'HTTP_X_PAYGATE_SIGNATURE' => $signature,
], $body);
}
$this->postJson() would encode the body itself, and the signature has to be computed over the exact bytes sent, so the helper drops to call(), which takes the raw body as its last argument and headers as server variables. test() is Pest's way to reach the current test case from a plain function. With the helper, the tests read like the provider's own checklist:
it('records a full payment, marks the invoice paid and emails a receipt', function () {
Mail::fake();
postWebhook(paymentEvent($this->invoice, ['reference' => 'pay_abc']))
->assertOk()
->assertJson(['status' => 'paid']);
$this->assertDatabaseHas('payments', ['invoice_id' => $this->invoice->id, 'reference' => 'pay_abc', 'amount' => 1200_00]);
expect($this->invoice->refresh()->status->value)->toBe('paid');
// The listener is queued, but the test queue is sync, so the mail was sent in-request.
Mail::assertSent(ReceiptMail::class, fn (ReceiptMail $mail) => $mail->hasTo('[email protected]')
&& $mail->invoice->is($this->invoice));
});
it('ignores a redelivered event instead of counting the money twice', function () {
Mail::fake();
$event = paymentEvent($this->invoice, ['reference' => 'pay_once']);
postWebhook($event)->assertOk();
postWebhook($event)->assertOk();
$this->assertDatabaseCount('payments', 1);
Mail::assertSent(ReceiptMail::class, 1);
});
it('rejects a body with a bad signature and records nothing', function () {
postWebhook(paymentEvent($this->invoice), secret: 'wrong-secret')->assertForbidden();
$this->post('/webhooks/payments', paymentEvent($this->invoice))->assertForbidden();
$this->assertDatabaseCount('payments', 0);
});
Mail::assertSent() with a closure passes only if some sent mailable of that class satisfies it; hasTo() checks the recipient and the mailable's own public properties are there to inspect. With an integer it asserts the count. The idempotency test is the one that will save you a refund: it posts the same event twice and expects one payment and one receipt, and the action makes that true by looking the reference up before doing anything.
The receipt goes out from a queued listener on an InvoicePaid event. The comment in the test matters: the listener is ShouldQueue, but phpunit.xml makes the queue synchronous, so the listener runs inside the request and the mail is already in the fake when the response comes back. If the suite used a real queue connection, Mail::assertSent would find nothing and the test would need Queue::fake() and an assertion on the listener instead. Know which one your phpunit.xml says.
Five more tests cover the partial payment (invoice stays sent, no receipt), partial payments that add up to the total, the currency mismatch (422 with a message, nothing stored), an unknown invoice (404) and event types the endpoint acknowledges and ignores. And one is about the event itself:
it('dispatches InvoicePaid with the invoice', function () {
// Faking one event switches off its listeners, so there is no receipt here. Say which
// events you fake; a bare Event::fake() would also silence model events such as creating.
Event::fake([InvoicePaid::class]);
postWebhook(paymentEvent($this->invoice));
Event::assertDispatched(InvoicePaid::class, fn (InvoicePaid $e) => $e->invoice->is($this->invoice));
Event::assertListening(InvoicePaid::class, SendReceipt::class);
});
Event::fake() with no arguments fakes every event, including Eloquent's model events, and factories that rely on creating or created hooks silently stop working. Pass the list. assertListening() checks the wiring without running the listener, which is the right test for "is this listener registered": Laravel 13 discovers listeners by type-hint, and a renamed event class would otherwise fail quietly.
A job that writes a file and sends it
Sending an invoice dispatches DeliverInvoice, a queued job that renders the PDF with dompdf to the invoices disk and mails it to the client with the file attached. Two tests, two fakes each.
The first proves that sending dispatches the job, and nothing more:
it('queues the delivery when an invoice is sent', function () {
Bus::fake();
$draft = Invoice::factory()->for($this->company)->for($this->client)
->has(InvoiceLine::factory(), 'lines')->create();
$this->actingAs($this->user)->post("/invoices/{$draft->id}/send")->assertRedirect();
Bus::assertDispatched(DeliverInvoice::class, fn (DeliverInvoice $job) => $job->invoice->is($draft));
});
Bus::fake() records dispatched jobs and runs none of them, so this test never renders a PDF. The second runs the job directly, with the disk and the mailer faked:
it('writes the PDF to the invoices disk and mails it to the client', function () {
Storage::fake('invoices');
Mail::fake();
$invoice = Invoice::factory()->for($this->company)->for($this->client)->sent()
->has(InvoiceLine::factory()->state(['description' => 'Brand guidelines', 'quantity' => 1, 'unit_price' => 2500_00, 'tax_rate' => 20]), 'lines')
->create(['number' => 'INV-2026-0003']);
$invoice->recalculate();
(new DeliverInvoice($invoice))->handle();
Storage::disk('invoices')->assertExists("{$this->company->id}/INV-2026-0003.pdf");
expect(Storage::disk('invoices')->get("{$this->company->id}/INV-2026-0003.pdf"))->toStartWith('%PDF-');
Mail::assertSent(InvoiceMail::class, function (InvoiceMail $mail) use ($invoice) {
$mail->assertHasSubject('Invoice INV-2026-0003 from Acme Studio')
->assertSeeInHtml('€3,000.00')
->assertHasAttachedData(Storage::disk('invoices')->get("{$this->company->id}/INV-2026-0003.pdf"), 'INV-2026-0003.pdf', ['mime' => 'application/pdf']);
return $mail->hasTo('[email protected]') && $mail->invoice->is($invoice);
});
});
Storage::fake('invoices') replaces the disk with a temporary folder that is emptied before the test, so the job writes a real file that the test can read. toStartWith('%PDF-') is as much as a test should know about a PDF's bytes. The mailable assertions, assertHasSubject(), assertSeeInHtml() and the attachment check, render the mail in the closure and throw if they fail, which is why the closure can run them before returning its boolean.
The attachment assertion has a trap worth the paragraph. The mailable returns Attachment::fromStorageDisk('invoices', $path)->as(...)->withMime(...) from attachments(), and the natural assertion is assertHasAttachmentFromStorageDisk(). It never matches. An Attachment object from a disk is read and attached as data when the mail is built; only the older $this->attachFromStorageDisk() call records a disk attachment. assertHasAttachedData() with the bytes, the name and the options is the assertion that sees it, and the disk fake is what makes the bytes available to compare.
An HTTP API, faked per request
Invoices in another currency show an approximate total in the company's currency at today's rate. ExchangeRates fetches a rate over HTTP and caches it for a day:
return Cache::remember("rates:{$from}:{$to}", now()->addDay(), function () use ($from, $to) {
try {
$rate = Http::timeout(5)
->retry(2, 100)
->get(config('services.rates.url'), ['base' => $from, 'symbols' => $to])
->throw()
->json("rates.{$to}");
} catch (RequestException|ConnectionException $e) {
throw new RatesUnavailable("Could not fetch the {$from}/{$to} rate.", previous: $e);
}
// ...
});
The tests never reach a network. The first line of the file makes sure of it:
beforeEach(function () {
// Any request that is not faked fails the test instead of leaving the laptop.
Http::preventStrayRequests();
});
it('fetches a rate and converts in minor units', function () {
// A closure fake answers from the request, so each base currency gets its own rate.
Http::fake(['rates.test/*' => fn (Request $r) => Http::response(['base' => $r['base'], 'rates' => [
'EUR' => ['USD' => 0.92, 'JPY' => 0.0062][$r['base']],
]])]);
$rates = new ExchangeRates;
expect($rates->rate('USD', 'EUR'))->toBe(0.92)
->and($rates->convert(100_00, 'USD', 'EUR'))->toBe(92_00)
->and($rates->convert(1000, 'JPY', 'EUR'))->toBe(620); // ¥1,000 at 0.0062 → €6.20: yen have no minor unit
Http::assertSent(fn (Request $r) => $r['base'] === 'USD' && $r['symbols'] === 'EUR');
});
it('caches a pair for a day so the API is hit once', function () {
Http::fake(['rates.test/*' => Http::response(['rates' => ['EUR' => 0.92]])]);
$rates = new ExchangeRates;
$rates->rate('USD', 'EUR');
$rates->rate('USD', 'EUR');
$rates->convert(5_00, 'USD', 'EUR');
Http::assertSentCount(1);
});
it('turns an API failure into a domain exception', function () {
Http::fake(['rates.test/*' => Http::response('upstream down', 503)]);
(new ExchangeRates)->rate('USD', 'EUR');
})->throws(RatesUnavailable::class, 'Could not fetch the USD/EUR rate.');
Http::fake() takes URL patterns and responses; a closure response gets the outgoing Request and can answer from it, which is how one fake serves two currencies. The host is rates.test because phpunit.xml sets RATES_URL to it; the production URL never appears in a test. assertSentCount(1) after three calls is the cache test, and CACHE_STORE=array in phpunit.xml is what makes the cache real but empty for each test. preventStrayRequests() is the line every suite should have somewhere: a test that forgets to fake a request fails loudly instead of depending on the weather at the API.
Two feature tests then check the page, one with a rate and one with a 500 that degrades to "rate unavailable". The controller catches the domain exception and the page still renders, which is the behaviour, so that is the test.
A command on the schedule
invoices:remind emails a reminder for every sent invoice past its due date, at most every three days, and runs every morning at nine. The client is not a user, so the notification goes on demand to an address:
Notification::route('mail', $invoice->client->email)->notify(new OverdueReminder($invoice));
$invoice->forceFill(['reminded_at' => now()])->save();
Its tests are the clock and the notification fake together:
beforeEach(function () {
Notification::fake();
$this->travelTo('2026-10-24 09:00');
$this->company = Company::factory()->create();
});
it('reminds the clients of overdue invoices and remembers that it did', function () {
$overdue = invoiceDueOn($this->company, '2026-10-20', '[email protected]', ['number' => 'INV-2026-0010']);
invoiceDueOn($this->company, '2026-10-30', '[email protected]');
invoiceDueOn($this->company, '2026-10-24', '[email protected]'); // due today is not overdue
$this->artisan('invoices:remind')
->expectsOutputToContain('INV-2026-0010: due 2026-10-20, [email protected]')
->expectsOutput('Reminded 1 client(s).')
->assertSuccessful();
Notification::assertSentOnDemand(OverdueReminder::class, fn (OverdueReminder $n, array $channels, AnonymousNotifiable $to) => $to->routes['mail'] === '[email protected]' && $n->invoice->is($overdue));
Notification::assertCount(1);
expect($overdue->refresh()->reminded_at->toDateTimeString())->toBe('2026-10-24 09:00:00');
});
it('waits three days between reminders', function () {
$invoice = invoiceDueOn($this->company, '2026-10-01', '[email protected]', ['reminded_at' => '2026-10-22 09:00']);
$this->artisan('invoices:remind')->expectsOutput('Reminded 0 client(s).');
Notification::assertNothingSent();
$this->travel(2)->days();
$this->artisan('invoices:remind')->expectsOutput('Reminded 1 client(s).');
Notification::assertSentOnDemand(OverdueReminder::class);
});
$this->artisan() runs the command in-process and returns a pending command whose expectsOutput() lines are checked when it runs; assertSuccessful() is the exit code. On-demand notifications have no notifiable model, so the fake offers assertSentOnDemand(), and the closure's third argument is the AnonymousNotifiable whose routes hold the address. The second test moves time with travel(2)->days() between two runs, which is the only honest way to test "every three days".
The notification's content is tested without sending it, by calling toMail() and reading the message, and the schedule registration with $this->artisan('schedule:list')->expectsOutputToContain('invoices:remind'), which is cheap insurance against a deleted line in routes/console.php. A --dry-run flag lists without sending and gets its own test, because the flag is what you will run first in production.
Run it
./vendor/bin/pest
PASS Tests\Feature\Billing\ExchangeRatesTest
PASS Tests\Feature\Console\SendOverdueRemindersTest
PASS Tests\Feature\Delivery\DeliverInvoiceTest
PASS Tests\Feature\Webhooks\PaymentWebhookTest
...
Tests: 112 passed (265 assertions)
The slowest test in the suite is now the one that renders a real PDF, at a quarter of a second. Everything the fakes replaced, mail, HTTP, the queue, costs nothing.
The part 4 commit has the middleware, the actions, the listeners, the job, the mailables, the notification, the command and the tests, with one follow-up for the attachment assertion described above.
What went wrong
Did not find the expected attachment. assertHasAttachmentFromStorageDisk() against a mailable whose attachments() returns Attachment::fromStorageDisk(). The attachment is attached as data, not recorded as a disk attachment. Assert on the bytes with assertHasAttachedData().
Unable to read file from location: x.pdf from (new InvoiceMail($invoice, 'x.pdf'))->render(). Rendering builds the complete message, attachments included, so even a test that only wants the HTML needs the file on a faked disk.
Failed asserting that 92000 is identical to 920. My yen conversion used the dollar's fake rate because the first fake answered every request with the same body. A closure fake that reads $request['base'] answers each currency correctly, and the expectation was wrong too: one thousand yen is one thousand yen, not ten.
Nothing failed, but it should have. A bare Event::fake() in an early draft of the webhook test also silenced the listener that sends the receipt, and the receipt assertion was not in that test, so it passed. Fake the events you mean to fake, by name.
Part 5 is about the database under all this, the factories that keep the setup short, how fast the suite can run, and the workflow that runs it on every push.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
4 / 6