Laravel feature and unit tests, with a real app · Part 3 of 6
Feature tests on the invoice flows
Create, edit, send, void and delete over HTTP: validation datasets, policies, a form request that authorises before it validates, frozen time, and an invoice number sequence that survives 9999.
By Abhishek Fouzdar · Updated
This part gives InvoiceMini its invoice flows, create, edit, show, send, void and delete, and tests them over HTTP: validation datasets, policies, a form request that authorises before it validates, frozen time for the dates, and a number sequence with a trap at 9999. It ends at 87 tests. Part 2 built the arithmetic; the series introduction explains InvoiceMini.
What a feature test is for
A feature test answers one question: when this request arrives, does the application do the right thing end to end? Routing, middleware, the form request, the controller, the policy, the queries, the response, in one go. It does not care how the controller is structured, which is why the controller can be restructured without touching the tests, and why a feature test that mocks the controller's collaborators has thrown away its own value.
The cost is setup: every test needs a company, a user and usually a client. Pest's beforeEach keeps that in one place per file:
beforeEach(function () {
$this->company = Company::factory()->create();
$this->user = User::factory()->for($this->company)->create();
$this->client = Client::factory()->for($this->company)->create(['name' => 'Northwind Traders']);
});
Properties set on $this in beforeEach are available in every test of the file. It runs inside the database transaction, so each test still starts clean.
Creating a draft
The form posts a client, a currency, a discount, notes and an array of lines. A helper at the top of the test file builds a valid payload and lets each test change one thing:
function invoicePayload(Client $client, array $overrides = []): array
{
return array_replace_recursive([
'client_id' => $client->id,
'currency' => 'EUR',
'discount_percent' => 0,
'notes' => null,
'lines' => [
['description' => 'Design work', 'quantity' => 2, 'unit_price' => 500_00, 'tax_rate' => 20],
['description' => 'Hosting', 'quantity' => 1, 'unit_price' => 20_00, 'tax_rate' => 20],
],
], $overrides);
}
Plain functions in a Pest file are fine; they are loaded once and shared by the tests in that file. The happy path checks the redirect, the stored record and the totals the model computed from the lines:
it('creates a draft with its lines and totals computed', function () {
$response = $this->actingAs($this->user)
->post('/invoices', invoicePayload($this->client));
$invoice = Invoice::sole();
$response->assertRedirect(route('invoices.show', $invoice));
expect($invoice)
->status->value->toBe('draft')
->number->toBeNull()
->company_id->toBe($this->company->id)
->subtotal->toBe(1020_00)
->tax->toBe(204_00)
->total->toBe(1224_00)
->lines->toHaveCount(2);
$this->assertDatabaseHas('invoice_lines', ['invoice_id' => $invoice->id, 'description' => 'Hosting', 'position' => 1]);
});
Invoice::sole() fetches the only row and throws if there are none or several, which is a better assertion than first() followed by a null check. expect($invoice)->status->value->toBe('draft') walks properties of the expected value: each ->name steps into that property and the next expectation applies to it. It is the compact way to check several attributes of one model. assertDatabaseHas() takes a table and the columns a row must have; here it checks that lines were stored in order.
Validation gets a dataset, one row per rule, and asserts both the error and that nothing was written:
it('rejects invalid submissions and names the field', function (array $overrides, string $field) {
$this->actingAs($this->user)
->from('/invoices/create')
->post('/invoices', invoicePayload($this->client, $overrides))
->assertRedirect('/invoices/create')
->assertSessionHasErrors($field);
$this->assertDatabaseCount('invoices', 0);
})->with([
'no lines' => [['lines' => null], 'lines'], // [] would merge into the defaults and change nothing
'zero quantity' => [['lines' => [0 => ['quantity' => 0]]], 'lines.0.quantity'],
'negative price' => [['lines' => [1 => ['unit_price' => -1]]], 'lines.1.unit_price'],
'tax over 100' => [['lines' => [0 => ['tax_rate' => 101]]], 'lines.0.tax_rate'],
'unknown currency' => [['currency' => 'XYZ'], 'currency'],
'discount over 100' => [['discount_percent' => 150], 'discount_percent'],
'missing description' => [['lines' => [0 => ['description' => '']]], 'lines.0.description'],
]);
Array rules produce dotted error keys, lines.0.quantity, and assertSessionHasErrors() takes them as they are. The comment on the first row is a trap I fell into: array_replace_recursive() with an empty array replaces nothing, so ['lines' => []] left both default lines in place and the test passed for the wrong reason. null replaces, and the required rule rejects it.
One rule deserves its own test, because it is where multi-tenancy usually leaks:
'client_id' => ['required', Rule::exists('clients', 'id')->where('company_id', $this->user()->company_id)],
it('refuses a client that belongs to another company, as if it did not exist', function () {
$foreign = Client::factory()->create();
$this->actingAs($this->user)
->post('/invoices', invoicePayload($foreign))
->assertSessionHasErrors('client_id');
$this->assertDatabaseCount('invoices', 0);
});
The rule scopes the existence check to the user's company, so another company's client id is simply invalid. Nothing in the response says the id exists elsewhere.
Policies, and 403 before 422
InvoicePolicy scopes everything to the user's company and freezes an invoice once it is sent: update, delete and send require a draft, void requires a status that can transition to void. The controller calls Gate::authorize('view', $invoice) on the show page, and the tests check both sides:
it('is forbidden for another company\'s user', function () {
$invoice = Invoice::factory()->create();
$this->actingAs($this->user)->get("/invoices/{$invoice->id}")->assertForbidden();
});
it('is not found for an id that does not exist', function () {
$this->actingAs($this->user)->get('/invoices/999999')->assertNotFound();
});
Whether another company's invoice should be a 403 or a 404 is a product decision; the test records whichever you made. InvoiceMini says 403, because the id space is shared and hiding existence buys nothing here.
Update is the interesting one. My first version authorised in the controller, after the form request had validated, and this test failed with Expected response status code [403] but received 302:
it('refuses to change an invoice that has been sent', function () {
$invoice = Invoice::factory()->for($this->company)->for($this->client)->sent()->create();
$this->actingAs($this->user)->get("/invoices/{$invoice->id}/edit")->assertForbidden();
$this->actingAs($this->user)
->put("/invoices/{$invoice->id}", ['client_id' => $this->client->id, 'currency' => 'EUR', 'lines' => []])
->assertForbidden();
});
The deliberately incomplete body hit validation first, and the response was a redirect with "the lines field is required" for an invoice the user was not allowed to touch. A form request's authorize() runs before its rules, so that is where the check belongs:
public function authorize(): bool
{
$invoice = $this->route('invoice');
return $invoice instanceof Invoice
? $this->user()->can('update', $invoice)
: $this->user()->can('create', Invoice::class);
}
One request class serves store and update, and the route parameter tells it which. The test that sends garbage to a forbidden route is the one that proves the order; a test with a valid body would pass either way.
Sending: numbers, dates, and the clock
Sending is an action class, not a controller method, because it has rules: a draft only, at least one line, the next number for the company's year, today as the issue date, the due date from part 2, and the Sent status, all inside a transaction with the number lookup locked.
DB::transaction(function () use ($invoice, $company, $today) {
$last = Invoice::lastNumber($company, $company->invoice_prefix, $today->year);
$invoice->recalculate();
$invoice->forceFill([
'number' => InvoiceNumber::next($last, $company->invoice_prefix, $today->year),
'status' => InvoiceStatus::Sent,
'issued_at' => $today,
'due_at' => DueDate::compute($today, $company->payment_terms_days),
])->save();
});
The test of the happy path has to control the clock, because the dates come from it:
it('numbers, dates and sends a draft', function () {
$this->freezeTime(); // the test runs at the same instant everywhere
$this->travelTo('2026-10-05'); // a Monday: due 14 days later is also a Monday
$invoice = draftFor($this->company, $this->client);
$this->actingAs($this->user)
->post("/invoices/{$invoice->id}/send")
->assertRedirect("/invoices/{$invoice->id}")
->assertSessionHas('status', 'Invoice INV-2026-0001 sent.');
$invoice->refresh();
expect($invoice)
->number->toBe('INV-2026-0001')
->status->value->toBe('sent')
->issued_at->toDateString()->toBe('2026-10-05')
->due_at->toDateString()->toBe('2026-10-19')
->total->toBe(120_00);
});
travelTo() sets Carbon's "now" for the rest of the test, and freezeTime() stops it moving, so now() in the action and now() in the assertion agree to the microsecond. Both are undone after the test. Every date assertion in the suite is a fixed string, which is what makes the suite pass on any day of the year; part 4 uses the same tools to test a scheduled command.
The sequence test creates the previous number and sends the next, and a second company in the same test to prove the sequences do not share:
it('continues the company\'s sequence and leaves other companies alone', function () {
$this->travelTo('2026-03-01');
Invoice::factory()->for($this->company)->for($this->client)->sent()->create(['number' => 'INV-2026-0041']);
$next = draftFor($this->company, $this->client);
$elsewhere = draftFor($other = Company::factory()->create(), Client::factory()->for($other)->create());
$this->actingAs($this->user)->post("/invoices/{$next->id}/send");
$this->actingAs(User::factory()->for($other)->create())->post("/invoices/{$elsewhere->id}/send");
expect($next->refresh()->number)->toBe('INV-2026-0042')
->and($elsewhere->refresh()->number)->toBe('INV-2026-0001');
});
And one test for the trap. "The highest number" is a string comparison in SQL, and INV-2026-10000 sorts before INV-2026-9999 as a string. The lookup orders by length first, then by value, which is portable and correct:
->orderByRaw('length(number) desc, number desc')
it('keeps counting past 9999, where a plain string sort would go wrong', function () {
$this->travelTo('2026-06-01');
Invoice::factory()->for($this->company)->for($this->client)->sent()->create(['number' => 'INV-2026-9999']);
Invoice::factory()->for($this->company)->for($this->client)->sent()->create(['number' => 'INV-2026-10000']);
$next = draftFor($this->company, $this->client);
$this->actingAs($this->user)->post("/invoices/{$next->id}/send");
expect($next->refresh()->number)->toBe('INV-2026-10001');
});
Nobody writes this test before the bug. Write it before the bug anyway; it costs six lines and it documents why the query is odd. The lockForUpdate() on the lookup is ignored by SQLite and honoured by MySQL, and part 5 runs the same suite against both.
The remaining send tests are the refusals: no lines (an error in the session, still a draft, still no number), already sent (403 from the policy), another company (403, and the number stays null). Void and delete get the same treatment in their own file: void a sent invoice and its number survives, voiding a paid one is 403, a draft can be deleted (assertModelMissing), a sent invoice cannot (assertModelExists).
The show page
Two assertions on the rendered page are worth knowing:
->assertSeeInOrder(['Two days of consulting', '€1,200.00', '€240.00', '€1,440.00']);
->assertDontSee('>Edit<', false)->assertDontSee('>Send<', false)->assertSee('Void');
assertSeeInOrder() checks the strings appear in that sequence, which is how you assert a table row reads correctly. The false second argument to assertDontSee() turns off escaping, so the test can look for >Edit<, the button's exact markup, rather than the word "Edit" that also appears in the page's title. Feature tests on HTML are brittle in proportion to how much HTML they assert on; a label and a total is the right amount.
Run it
./vendor/bin/pest
PASS Tests\Feature\Invoices\CreateInvoiceTest
PASS Tests\Feature\Invoices\RecalculateTest
PASS Tests\Feature\Invoices\SendInvoiceTest
PASS Tests\Feature\Invoices\ShowInvoiceTest
PASS Tests\Feature\Invoices\UpdateInvoiceTest
PASS Tests\Feature\Invoices\VoidAndDeleteInvoiceTest
...
Tests: 87 passed (194 assertions)
Duration: 1.09s
The part 3 commit has the controller, the form request, the policy, the two actions, the views and the tests.
What went wrong
Three tests failed on the first run of this part, and each one was the test being right.
A draft page showed a Void button. The enum allowed draft to void; the policy faithfully offered it. The test asserting assertDontSee('Void') on a draft was encoding a decision nobody had made yet. Drafts are deleted, not voided; the enum changed, and part 1's dataset gained its last line.
Expected response status code [403] but received 302. Validation ran before authorization. Moving the check into the form request's authorize() fixed the order, and the test with the incomplete body is the one that keeps it fixed.
The "no lines" validation case passed without validating. array_replace_recursive() treats an empty array as "nothing to replace". A helper that merges payloads needs a way to say "remove this", and null is it.
Call to undefined method on Invoice::factory()->draft() in the seeder, again. Factory states are methods; if you call one, write it.
Part 4 is where the application talks to the outside world, and the tests have to stand in for it: a payment provider's webhook, the queue, mail, storage, an HTTP API and the scheduler.
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
3 / 6