Kritim Yantra
Mar 04, 2025
Testing is a crucial part of building reliable web applications. It helps ensure your code works as expected and prevents bugs from sneaking into production. If you're using Laravel, one of the most popular PHP frameworks, you have access to excellent testing tools. Among them, Pest stands out as a beginner-friendly testing framework that makes writing tests simple, readable, and fun.
In this detailed tutorial, we’ll walk through everything you need to know to get started with Pest testing in Laravel. We’ll cover what Pest is, how to install it, how to write different types of tests (like testing pages, databases, and APIs), and some best practices—all explained in simple terms with plenty of example code. Whether you're new to testing or Laravel, this guide is designed to help you understand and start testing your applications with confidence.
Pest is a testing framework for PHP that’s built on top of PHPUnit, a widely-used testing library. While PHPUnit is powerful, its syntax can feel a bit clunky and hard to read for beginners. Pest fixes this by offering a cleaner, more expressive way to write tests. It’s especially great for Laravel developers because it works seamlessly with Laravel’s built-in testing tools.
With Pest, your tests read more like plain English descriptions of what your app should do. This makes it easier to understand what each test is checking—even if you’re new to programming.
Before you can start writing tests, you need to set up Pest in your Laravel project. Don’t worry—it’s super easy! Follow these step-by-step instructions:
Composer is a tool that manages PHP dependencies (libraries and frameworks). To install Pest, open your terminal, navigate to your Laravel project’s folder, and run:
// Run this in your terminal:
composer require pestphp/pest --dev
The --dev
flag tells Composer to only include Pest when developing, not in your production app.
Once Pest is installed, initialize it in your Laravel project by running:
// Run this in your terminal:
php artisan pest:install
This command creates the necessary files and folders (like the tests directory) that Pest uses. You’re now ready to start testing!
Pest tests are written in PHP files inside the tests
directory of your Laravel project. Typically, this directory contains two subfolders:
In Pest, you define tests using two main functions: it
or test
. Both work the same way—they let you write a test with a clear description of what the test does.
Let’s start with a simple example: testing that your Laravel app’s homepage loads correctly (returns a 200 status code, which means "success").
Step 1: Create a test file in the tests/Feature
folder called HomepageTest.php
.
Step 2: Add the following code to HomepageTest.php
:
<?php
it('can visit the homepage', function () {
$response = $this->get('/');
$response->assertStatus(200);
});
This test simulates visiting the root URL (/
) and asserts that the response status is 200.
Step 3: Run your test with:
<?php
// Run in your terminal:
php artisan test
If your homepage is set up (by default, Laravel shows a welcome page), you should see a green "PASS" message.
Next, we’ll test saving and finding data in a database. Assume your app has a Post
model (for blog posts) with title
and content
fields.
Step 1: Create the Post model with a migration if you haven't already:
<?php
// Run in terminal:
php artisan make:model Post -m
Then, edit the migration file (e.g., 2023_XX_XX_create_posts_table.php
) to add fields:
<?php
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Run the migration:
<?php
php artisan migrate
Step 2: Create a test file called PostTest.php
in tests/Feature
and add the following:
<?php
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('can create a post', function () {
$post = Post::create([
'title' => 'My First Post',
'content' => 'This is my first post’s content.',
]);
$this->assertDatabaseHas('posts', [
'title' => 'My First Post',
]);
});
The uses(RefreshDatabase::class)
call resets the database between tests. This test creates a post and asserts that the database contains a post with the specified title.
Step 3: Run your test with php artisan test
.
Finally, let’s test API endpoints. We’ll cover retrieving a list of posts and creating a new post via the API.
Step 1: Create a PostController
with API methods:
<?php
// app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return Post::all();
}
public function store(Request $request)
{
$post = Post::create($request->all());
return response()->json($post, 201);
}
}
Then, define API routes in routes/api.php
:
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
Route::get('/posts', [PostController::class, 'index']);
Route::post('/posts', [PostController::class, 'store']);
Step 2: Create a test file called ApiPostTest.php
in tests/Feature
to test the API endpoints.
To test a GET request:
<?php
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('can retrieve posts via API', function () {
// Create 3 fake posts using a factory (ensure a factory is defined for Post)
Post::factory()->count(3)->create();
$response = $this->getJson('/api/posts');
$response->assertStatus(200)
->assertJsonCount(3);
});
To test a POST request:
it('can create a post via API', function () {
$data = [
'title' => 'New API Post',
'content' => 'This post was created via API.',
];
$response = $this->postJson('/api/posts', $data);
$response->assertStatus(201)
->assertJsonFragment($data);
$this->assertDatabaseHas('posts', $data);
});
Step 3: Run your API tests with php artisan test
.
it('can create a post')
so anyone can understand what the test does.Post::factory()
) to create test data quickly and consistently.RefreshDatabase
to ensure tests don’t interfere with each other.Congratulations! You’ve just learned how to use Pest to test your Laravel applications. We covered installing Pest, testing a webpage, working with databases, and checking API endpoints—all with simple, detailed examples.
Pest’s readable syntax makes testing approachable, even for beginners. While testing might feel like extra work at first, it saves you time by catching bugs before they become big problems.
Keep practicing, and soon you’ll be writing tests like a pro.
Happy testing!
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google