Test-driven development (TDD) is an essential aspect of software development, providing the confidence and peace of mind to continuously make improvements and updates to your application. In this article, we’ll look at how to get started with Test-Driven Development using the PHP testing framework called Pest.
- Setting Up Pest
Before we start writing tests with Pest, we need to install it. We can do this using composer by running the following command:
composer require pestphp/pest --dev
Once we’ve installed Pest, we need to set it up. We can do this by creating a Pest.php
file in the root directory of our project:
// Pest.php
uses(Tests\TestCase::class)->in('Feature');
uses(Tests\TestCase::class)->in('Unit');
- Writing A Test
Let’s write a simple test to ensure that a product can be created in our application. In our tests/Feature/
directory, we’ll create a ProductTest.php
file:
// tests/Feature/ProductTest.php
test('a product can be created', function () {
$product = Product::factory()->create([
'name' => 'Laptop',
'price' => '1000',
]);
$this->assertDatabaseHas('products', [
'name' => 'Laptop',
'price' => '1000',
]);
});
In the example above, we’re creating a new product and asserting that it exists in the database. This will fail until we’ve created the Product
model and added it to our application.
With these examples, you should now have a basic understanding of how to get started with Test-Driven Development using Pest in Laravel. Remember to start small, get comfortable with the process, and expand your tests as needed. Happy testing!
Sources: