Behavioural Driven Development in Laravel

Published on by

Behavioural Driven Development in Laravel image

BDD, or Behavioural Driven Development, is a popular testing approach in many organizations and has a proven track record for uniting testing efforts across teams. But the question remains, how can we achieve this in Laravel without having to learn a new framework for testing or new language syntax such as Gherkin.

As a business being able to define processes in an easy-to-read way and for that to be represented in our test suites is a huge benefit. Much like Domain Driven Design allows us to create a ubiquitous language for our code, BDD will enable us to have a ubiquitous language for our testing.

Let's walk through some examples of what a BDD test might look like, and then let us break this down. Let us imagine that we have a web application that has a registration form. When this form is completed, we expect that the user will be registered, and they should be automatically logged in. Let us look at this in a typical feature test:

it('allows a user to register for an account', function (string $email) {
expect(
User::query()->count(),
)->toEqual(0);
 
post(
route('register'),
['name' => 'test', 'email' => $email, 'password' => 'password']
)->assertRedirect(route('dashboard'));
 
expect(
User::query()->count(),
)->toEqual(1);
})->with('emails');

This is a simple example of what you could do with pestPHP to test this endpoint, which replicates a form submission. As you can see, as a developer, this is relatively easy to understand if you are used to testing with pest. However, your QA Engineer will struggle with this as they are not used to pestPHP, and it doesn't have a syntax they understand.

How could we refactor this to use BDD and a syntax our QA Engineer and the wider team may understand? Luckily, a pestPHP plugin will allow us to use a "Given When Then" approach, which is typical in the BDD world. This is the Give when then plugin and is straightforward to get started with. Run the following composer command to install this plugin:

composer require milroyfraser/pest-plugin-gwt --dev

From here, we can start writing specific tests for BDD. One thing we want to bear in mind at this point is, do we want to replace our tests, or do we want BDD to enhance our current test suite? I would look to improve my existing test suite to avoid losing valuable tests.

Let us take an example I recently encountered. I was not using any specific Auth package for my Laravel application. Instead, I needed to create a custom authentication flow - using a one-time password. My register form is a Livewire component that handles the logic for me. So let us first write the feature test to ensure our component works.

it('will submit the form and create a new user', function (string $email) {
Livewire::test(
RegisterForm::class,
)->set(
'name', 'test',
)->set(
'email', $email,
)->set(
'password', 'password',
)->call(
'submit'
)->assertHasNoErrors(
['name', 'email', 'password']
);
})->with('emails');

We are testing that we can fill in and submit the form. We could add our expectations around this to ensure that the user is created in the database, but we can simplify our feature test here and move some of this logic to an Integration test.

In our case, like most of my code, I perform the logic in Action classes, so moving this makes a lot of sense. I typically have single action classes for all read and write operations I need to perform so that CLI, Web, and API can use all similar logic - the only difference is how it is called. In the above example, our Livewire component would call the action to create the user.

So now, let us look at what the business process would look like in a Gherkin syntax:

Scenario: The Register Action is handled
Given the RegisterAction is created
When the handle method is called
Then a new user will be created

Admittedly we could write this in a standard test, and it would make sense to us as developers - but one of the principles of DDD I love is the ubiquitous language you create - almost like a business language.

For our BDD tests, I will create an Integration directory under test, so that I have: Unit: Test-Driven Development Feature: Test-Driven Development Integration: Behavioral Driven Development

Inside our Integrations directory, we will store all of our scenarios created as pestPHP tests using the plugin we installed.

scenario('The RegisterAction is handled')
->given(fn () => new RegisterAction())
->when(fn (RegisterAction $action) => $action->handle(
name: 'test',
email: 'pest@test.com',
password: 'password',
))->then(fn () => assertDatabaseHas('users', [
'name' => 'test',
'email' => 'pest@test.com',
]));

As you can see from the above code, it is effortless to understand. It has great similarities to what we might expect in most BDD test suites - but in a framework, we are used to. We can usually directly translate this to a user story in many cases.

Let us take one more example, but this time we will start from a user story:

As a User, when I activate my account, I must receive an email.

Now let us move this to Gherkin syntax:

Scenario: A user can activate their account
Given a new user
When they activate their account
Then an email is sent to confirm the activation.

Finally, let us move on to pestPHP with the plugin we are testing:

scenario('A user can activate their account')
->given(fn (): User => User::factory()->inactive()->create())
->when(fn () => Bus::fake())
->when(fn (User $user): User => $user->activate())
->then(function (User $user) {
Bus::assertDispatched(ActivateUser::class);
});

So you can see that this way of testing has advantages for your test suite and your team. I am not saying you should always use this approach - but for those critical business processes, it allows you to map the process from a language the business understands to a test suite you understand directly.

Have you found any other exciting ways to improve your testing strategy in your applications? Let us know your thoughts on Twitter!

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project.

Visit No Compromises
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Add Kanban Boards to Your Laravel App in Seconds image

Add Kanban Boards to Your Laravel App in Seconds

Read article
October CMS v3.6 Ships Today, Full of New Features image

October CMS v3.6 Ships Today, Full of New Features

Read article
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article
Use Google's Gemini AI in Laravel image

Use Google's Gemini AI in Laravel

Read article
PhpStorm is getting a brand new terminal image

PhpStorm is getting a brand new terminal

Read article
Six Essential Plugins for Visual Studio Code image

Six Essential Plugins for Visual Studio Code

Read article