How to get started with Behat

Automated testing is one of the resources that greatly facilitates the task of development and one of the tools we can use with good integration with Drupal is Behat. It's an open source framework for behavioral testing, and that means that the testing is done using the web as a user would do.

One of its main strengths is its readability: it is written in natural language describing the behavior to be tested, and allows us to check at any time if our application behaves as expected.

In Ymbra we find it especially useful to know if any new changes we have made to the code produces some regression in functionality, which can easily pass unnoticed and take some time to be detected.

What do we need to start

To integrate Behat with Drupal it's advisable to use Drupal Extension, an integration layer that provides definitions of steps for testing specific scenarios that you can find on websites developed with Drupal.

We'll start by installing Behat with Composer with the following command:

 

php composer.phar require --dev drupal/drupal-extension=~3.1

that will create the composer.json file in the project root.

And then we will create the behat.yml file in which we will include our basic configuration:

 

    default:
        suites:
        default:
            contexts:
              - Drupal\DrupalExtension\Context\DrupalContext
    extensions:
      Behat\MinkExtension:
        goutte: ~
        base_url: http://example.org/  # Replace with your site's URL
      Drupal\DrupalExtension:
        blackbox: ~

With the command:

 

    vendor/bin/behat --init

the FeatureContext.php file will be created, where custom steps to be executed later can be defined.

You may find detailed information about the installation process in the Drupal Extension documentation.

How to write the first test

Our file foo.feature will include a feature containing one or more scenarios depending on our needs. The scheme will be as follows:

 

    Feature: (title)
      In order to (benefit)
      As a (role)
      I need to (feature) 

For example:

      Feature: Test Publications
        In order to see interesting publications
        As a visitor
        I need to see a page to view them

 

Then we will add the scenarios with their description, actions to be taken and expected outcome.

 

      Scenario: (title)
      Given (context)
      When (action)
      Then (outcome)

For example:

 

      Scenario: Publications list
      Given I am an anonymous user
      And I am on "/"
      When I click "Publicaciones"
      Then the url should match "actualidad/publicaciones$"
      And I see the heading "Publicaciones"
      # Eight publications.
      And I should see 8 ".view-publications .item-list > li" elements
      # There is a pager.
      And I should see a ".pager" element
    


In this example we want to test that an anonymous user is able to view a particular section, "Publications", the pathauto is properly configured, the default content of a list of publications created through a view has been successfully migrated, and that it displays a pager.

 

As it can be seen, each scenario consists of a set of steps that must begin with one of the keywords Given, When, Then, But or And.

To check all the steps that we have available we can use the command:

 

    vendor/bin/behat -dl

In the following complete example we can see how Behat is useful to test the fields displayed in a form and its validation.

 

    Feature: Test fundraising forms
      In order to participate in the company cause.
      As a visitor
      I need to see and send a form with my data.

      @api @javascript
      Scenario: Visit a form and check the count.
      Given I am an anonymous user
      And I am on "/colabora"
      Then I should see the text "¡Ya somos 100 firmantes!"
      And I fill in "Nombre" with "Juan"
      And I fill in "Primer Apellido" with "Perez"
      And I fill in "Población" with "Villarriba del rio"
      And I select "BADAJOZ" from "Província"
      Given I press "Enviar" in the content region
      And I go to "/colabora"
      Then I should see the text "¡Ya somos 101 firmantes!"

      @api
      Scenario: Visit a form and check the display and validations after introducing invalid data.
      Given I am an anonymous user
      And I am on "/donativo"

      # Introducing an invalid bank account
      When I fill in "IBAN" with "ES18"
      When I fill in "Entidad" with "0049"
      When I fill in "Oficina" with "15000"
      When I fill in "DC" with "ab"
      When I fill in "Cuenta" with "2710151321"

      When I press the "Haz un donativo" button

      Then I should see the following error messages:
        | error messages             |
        | El campo DC debe ser numérico. |
        | El campo Oficina debe contener exactamente 4 dígitos, "15000" tiene 5 dígitos. |
        | El IBAN no es válido. |

In the first scenario we want to test whether when an anonymous user accepts a form the subsequent redirection is successful and if a signatures counter is updated.

With the second we want to check if the expected error messages are displayed when an anonymous user enters wrong bank data in a donation form. There is no need to run a step for checking each of the errors, we have available the option to create an array of strings to evaluate all of them in the same step.

In the first scenario @javascript allows us to open a web browser which also can generate screenshots of the errors that occur. Selenium and Phantom.js are the most used tools to execute Behat in real browsers.

Once we have written our test we can run it with the following command:

 

    vendor/bin/behat

If the test runs without errors it will inform us how many scenarios and steps have been overcome successfully. Otherwise we will see the number of steps that have failed and which they are specifically.

Conclusion

Behat is a recommended tool for its ability to make the testing friendly, and the easy understanding of the tests allows that they become written and maintained by other professional profiles in addition to the developers.

It can also be used to show the stakeholders 1 of a project in which we are working to validate the features they want, and check if both stakeholders and developers are working with the same understanding of what needs to be developed.

You may find much more detailed information for further introduction in the official documentation.

1. The people involved in the project, not necessarily just the end customer, which needs to be taken into account.