Behavioural Driven Development in Laravel


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:

1it('allows a user to register for an account', function (string $email) {

2 expect(

3 User::query()->count(),

4 )->toEqual(0);

5 

6 post(

7 route('register'),

8 ['name' => 'test', 'email' => $email, 'password' => 'password']

9 )->assertRedirect(route('dashboard'));

10 

11 expect(

12 User::query()->count(),

13 )->toEqual(1);

14})->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:

1composer 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.

1it('will submit the form and create a new user', function (string $email) {

2 Livewire::test(

3 RegisterForm::class,

4 )->set(

5 'name', 'test',

6 )->set(

7 'email', $email,

8 )->set(

9 'password', 'password',

10 )->call(

11 'submit'

12 )->assertHasNoErrors(

13 ['name', 'email', 'password']

14 );

15})->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:

1Scenario: The Register Action is handled

2 Given the RegisterAction is created

3 When the handle method is called

4 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.

1scenario('The RegisterAction is handled')

2 ->given(fn () => new RegisterAction())

3 ->when(fn (RegisterAction $action) => $action->handle(

4 name: 'test',

5 email: 'pest@test.com',

6 password: 'password',

7 ))->then(fn () => assertDatabaseHas('users', [

8 'name' => 'test',

9 'email' => 'pest@test.com',

10 ]));

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:

1Scenario: A user can activate their account

2 Given a new user

3 When they activate their account

4 Then an email is sent to confirm the activation.

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

1scenario('A user can activate their account')

2 ->given(fn (): User => User::factory()->inactive()->create())

3 ->when(fn () => Bus::fake())

4 ->when(fn (User $user): User => $user->activate())

5 ->then(function (User $user) {

6 Bus::assertDispatched(ActivateUser::class);

7 });

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!

Source link

Share

Leave a Reply

Your email address will not be published. Required fields are marked *