Last updated: 15 November 2026. Series: Part 1 of 3. Tested on Laravel 13.40, PHP 8.3.6, Pest 4.7.8 and PHPUnit 12.5.33. The current Pest release is 5, which needs PHP 8.4; seeWhich Pest version?. Update log at the end.
Most Laravel projects start with the two example tests and never get further, because the next step, testing a real endpoint with authentication, validation, a payment call and a database write, is where the tutorials stop. This series builds that test suite step by step. Part 1 installs Pest and writes feature tests for an order endpoint. Part 2 covers mocking and fakes, and Part 3 covers organizing the suite and running it in CI.
Which Pest version?
| Pest | PHP | PHPUnit |
|---|---|---|
| 5.x (current) | 8.4+ | 13 |
| 4.x | 8.3+ | 12 |
That comes from the Pest documentation and upgrade guide, which describe the 4 to 5 upgrade as a one-line change to composer.json for most suites. Every example in this series ran on Pest 4.7.8, because my environment has PHP 8.3. The test code uses only it(), expect(), datasets and Laravel's own test helpers, none of which the upgrade guide lists as changed, but I did not run Pest 5, so check it on your project.
Install Pest in a Laravel project
The documented steps for a project that currently uses PHPUnit:
composer remove phpunit/phpunit
composer require pestphp/pest --dev --with-all-dependencies
composer require pestphp/pest-plugin-laravel --dev
./vendor/bin/pest --init
The second package is the Laravel plugin. It adds Laravel helpers such as mock() and spy() as functions and some Artisan commands. --init creates tests/Pest.php. I could not run these commands (my environment cannot reach the Composer package index, so I assembled the packages from their source), so follow the Pest installation page if your output differs. Then make tests/Pest.php look like this, so every feature test gets the Laravel application and a clean database:
<?php
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
pest()->extend(TestCase::class)
->use(RefreshDatabase::class)
->in('Feature');
Laravel's default phpunit.xml already sets DB_CONNECTION=sqlite and DB_DATABASE=:memory:, so tests run against an in-memory SQLite database. That is fast, but it is not your production engine; if your queries use MySQL-specific features, run the suite against MySQL in CI as well.
To create a test file with Pest syntax, I used (and it produced a Pest-style file):
php artisan make:test OrderTest --pest
The code under test
A small orders API: an authenticated user posts a product and a quantity, the app charges a payment gateway, saves the order and fires an event. This is the code every test in the series exercises.
// routes/web.php
Route::middleware('auth')->group(function () {
Route::post('/orders', [OrderController::class, 'store']);
Route::get('/orders/{order}', [OrderController::class, 'show']);
});
// app/Payments/PaymentGateway.php
interface PaymentGateway
{
/** @throws PaymentFailed */
public function charge(int $amountCents, string $token): string;
}
// app/Payments/HttpPaymentGateway.php
class HttpPaymentGateway implements PaymentGateway
{
public function charge(int $amountCents, string $token): string
{
$response = Http::withToken(config('services.payments.key'))
->acceptJson()
->post(config('services.payments.url').'/charges', [
'amount' => $amountCents,
'source' => $token,
]);
if ($response->failed()) {
throw new PaymentFailed($response->json('error', 'Payment was declined.'));
}
return $response->json('id');
}
}
// app/Http/Controllers/OrderController.php
public function store(Request $request, PaymentGateway $gateway): JsonResponse
{
$prices = config('shop.prices'); // ['book' => 1500, 'mug' => 800], in cents
$data = $request->validate([
'sku' => ['required', 'string', Rule::in(array_keys($prices))],
'quantity' => ['required', 'integer', 'min:1', 'max:10'],
'payment_token' => ['required', 'string'],
]);
$total = $prices[$data['sku']] * $data['quantity'];
try {
$reference = $gateway->charge($total, $data['payment_token']);
} catch (PaymentFailed $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
$order = $request->user()->orders()->create([
'sku' => $data['sku'],
'quantity' => $data['quantity'],
'total_cents' => $total,
'payment_reference' => $reference,
]);
GenerateInvoice::dispatch($order);
OrderPlaced::dispatch($order);
return response()->json(['id' => $order->id, 'total_cents' => $total], 201);
}
public function show(Order $order): JsonResponse
{
$this->authorize('view', $order); // OrderPolicy: $order->user_id === $user->id
return response()->json($order->only(['id', 'sku', 'quantity', 'total_cents', 'status']));
}
The service provider binds the interface to the HTTP implementation: $this->app->bind(PaymentGateway::class, HttpPaymentGateway::class);. That binding is what makes the payment call replaceable in tests (Part 2). The Order and User models, the OrderPolicy, the OrderFactory and the orders migration are ordinary Laravel; the factory gives each order a user_id, book as the SKU and 1500 cents as the total.
Feature tests
A feature test sends a request through the whole framework (routing, middleware, validation, database) and asserts on the response and the database. Here is the first version of tests/Feature/OrderTest.php:
<?php
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
config(['services.payments.url' => 'https://payments.example.test']);
$this->user = User::factory()->create();
});
it('shows the home page', function () {
$this->get('/')->assertOk()->assertSee('Shop');
});
it('rejects guests', function () {
$this->postJson('/orders', [])->assertUnauthorized();
});
it('creates an order and charges the card', function () {
Http::fake([
'payments.example.test/charges' => Http::response(['id' => 'ch_123'], 201),
]);
$response = $this->actingAs($this->user)->postJson('/orders', [
'sku' => 'book',
'quantity' => 2,
'payment_token' => 'tok_visa',
]);
$response->assertCreated()->assertJson(['total_cents' => 3000]);
$this->assertDatabaseHas('orders', [
'user_id' => $this->user->id,
'sku' => 'book',
'quantity' => 2,
'total_cents' => 3000,
'payment_reference' => 'ch_123',
]);
Http::assertSent(fn ($request) => $request['amount'] === 3000 && $request['source'] === 'tok_visa');
});
Things worth noticing:
-
$this->userset inbeforeEachis available in every test in the file. In Pest,$thisinside a test closure is the test case, so every Laravel helper (get,actingAs,assertDatabaseHas) works as in PHPUnit. -
postJson()sendsAccept: application/json, so a guest gets a 401 instead of a redirect to the login page. -
Http::fake()stops the real HTTP request and returns a canned response.Http::assertSent()then checks what your code sent, which proves the amount is computed server-side (3000 for two books), not trusted from the client. - The database assertion checks the stored values, not just the status code. A 201 response with nothing saved would pass a status-only test.
Validation with datasets
Five invalid payloads would be five copy-pasted tests. A dataset runs one test body once per row, and each row gets a name that shows up in the output:
it('validates the request', function (array $payload, string $field) {
$this->actingAs($this->user)
->postJson('/orders', $payload)
->assertUnprocessable()
->assertJsonValidationErrors($field);
})->with([
'missing sku' => [['quantity' => 1, 'payment_token' => 't'], 'sku'],
'unknown sku' => [['sku' => 'car', 'quantity' => 1, 'payment_token' => 't'], 'sku'],
'zero quantity' => [['sku' => 'book', 'quantity' => 0, 'payment_token' => 't'], 'quantity'],
'too many' => [['sku' => 'book', 'quantity' => 11, 'payment_token' => 't'], 'quantity'],
'no token' => [['sku' => 'book', 'quantity' => 1], 'payment_token'],
]);
Failure paths and authorization
it('returns 422 and saves nothing when the card is declined', function () {
Http::fake(['*' => Http::response(['error' => 'Card declined'], 402)]);
$this->actingAs($this->user)
->postJson('/orders', ['sku' => 'mug', 'quantity' => 1, 'payment_token' => 'tok_bad'])
->assertUnprocessable()
->assertJson(['message' => 'Card declined']);
$this->assertDatabaseCount('orders', 0);
});
it('lets owners view their own order only', function () {
$order = Order::factory()->for($this->user)->create();
$this->actingAs($this->user)->getJson("/orders/{$order->id}")
->assertOk()
->assertJsonPath('sku', 'book');
$this->actingAs(User::factory()->create())->getJson("/orders/{$order->id}")
->assertForbidden();
});
The ownership test is the one most worth having. It is a security check: without it, any logged-in user can read any order by changing the ID in the URL. Make a habit of testing both the allowed and the forbidden user in the same test.
Run it
./vendor/bin/pest
Output from my run of this file (timings trimmed):
PASS Tests\Feature\OrderTest
✓ it shows the home page
✓ it rejects guests
✓ it creates an order and charges the card
✓ it validates the request with dataset "missing sku"
✓ it validates the request with dataset "unknown sku"
✓ it validates the request with dataset "zero quantity"
✓ it validates the request with dataset "too many"
✓ it validates the request with dataset "no token"
✓ it returns 422 and saves nothing when the card is declined
✓ it lets owners view their own order only
Tests: 10 passed (28 assertions)
Useful flags I ran: --filter="declined" runs matching tests only, --compact prints dots instead of one line per test, and --bail stops at the first failure.
Do the tests actually catch bugs?
A passing test proves little until you see it fail. I changed max:10 to max:20 in the controller and reran the suite. The "too many" dataset row failed with Expected response status code [422] but received 500: quantity 11 now passed validation and the request went on to the real gateway call, which that test does not fake. Restoring max:10 brought the suite back to green. Try this kind of deliberate break on your own critical rules once; it also shows whether your failure messages are readable.
Common mistakes
-
Unit tests have no Laravel app. A test in
tests/Unitthat callsconfig()failed withTarget class [config] does not exist, becausetests/Pest.phponly extendsTestCasefor theFeaturedirectory. Adduses(Tests\TestCase::class);at the top of that file (this worked), or extend the folder inPest.php. Chaining->uses(TestCase::class)onto a single test did not boot the app in my run, so I would use the file-level call. -
Forgetting to fake the HTTP call. Without
Http::fake()the test tries the real network. Part 2 showsHttp::preventStrayRequests()to make that an error. - Asserting only the status code. Check the database and the response body too.
- Testing against SQLite only when production runs MySQL or PostgreSQL. Run CI against your real engine.
-
Using the production
.envin tests. The values inphpunit.xmloverride it; keep real credentials out of the test run entirely.
Related Dev Talk articles
- Laravel Custom Validation Rules: Rule Classes, Closures, Data-Aware Rules and Tests
- Laravel Multiple Databases: Connections, Models, Migrations and Transactions
- Laravel Activity Log with Spatie: Track User Actions and Model Changes
Frequently asked questions
Is Pest better than PHPUnit?
Pest runs on top of PHPUnit, so you keep its engine and Laravel's helpers. The difference is syntax and some extras (datasets, expectations, architecture tests). Existing PHPUnit tests can run alongside Pest tests.
Do I need Mockery for feature tests?
Not for Part 1. Http::fake() and the database cover this file. Mockery appears in Part 2.
Should I use RefreshDatabase or DatabaseTransactions?
This series uses RefreshDatabase with in-memory SQLite. If you test against a persistent database, read Laravel's testing documentation on the differences before choosing.
Which Laravel versions does this apply to?
I ran Laravel 13.40. The Laravel test helpers used here (actingAs, postJson, assertDatabaseHas, Http::fake) have been in Laravel for several major versions, but I did not run older ones.
update log
- 15 November 2026: first published.
-
To recheck on each update: the current Pest version and PHP requirement, and the output of
pest --init.
Sources
- Pest documentation: Installation
- Pest documentation: Upgrade guide
- Pest documentation: Plugins (Laravel)
- Laravel documentation: HTTP tests
- Laravel documentation: HTTP client testing
Originally published on DEV Talk.
Top comments (0)