How To Test A Drupal Website With Behat? ⋆ Appic Softwares

How To Test A Drupal Website With Behat?

Drupal Website

The ability to collaborate effectively and develop software is facilitated by the power of tales as well as clear and effective communication. The Behavior Driven Development (BDD) tools, which evolved out of agile methodology, make the most of this power to the best extent possible in order to automate the testing process. One of these BDD technologies is called Behat, and it facilitates automated testing by making use of “ubiquitous language.” Let’s get more familiar with Behat, Mink, and Gherkin, as well as the process of implementing it in Drupal.

What is Behat?

Behat is an open-source PHP framework that was developed for the purpose of automating testing through the utilization of Behavior Driven Development (BDD). By putting an emphasis on constant communication and straightforward text storytelling, a BDD strategy guarantees the delivery of high-quality software. Using BDD, the tester will construct test cases using language that is readable by humans. Because of this, it is simple to get the entire team on the same page because everyone, starting with the product owner and working all the way down to the developer, is able to comprehend the present scenario and receive continuous feedback on it

What is Gherkin?

The Behat tool communicates with users via the Gherkin language, which is a domain-specific language that is also legible by businesspeople. Additionally, Gherkin acts as a living documentation, and reports can be generated to document each individual test run. This language is based primarily on whitespace, and its keywords are words from simple languages. The structure of the test case is determined by the use of line endings and indentation (using space or tab). Even if it is simple to write in and understand the language, the end result should center on improving collaboration, efficiency, automation, and traceability. It is crucial that test cases be written in an intuitive manner, with a concentration on important aspects, while avoiding testing duplicate entries and employing correct syntax. 

What is Mink?

A test scenario with the online application can be simulated using Mink, which is a browser controller that is open source. After the test cases have been prepared, they need to be run and should simulate how users would behave. You may run the same test scenario on many browser emulators with Mink, including Goutte, Selenium, Chrome, Zombie, and many others. You will notice a requirement on Mink while installing the Behat Drupal extension; therefore, you need to ensure that you already have Mink installed on your system.

Installation and implementation of Behat in Drupal

Composer is the recommended method for installing Behat in a Drupal project, as this is the official method. Not only will it install Behat for you, but in the event that an updated version is released in the future, it will also be able to effortlessly update you to the most recent version.

  • Within the folder containing the project, carry out the following command:
$ composer require behat/behat
  •  Alternatively, you can include the require statement within your composer.json file.
  "require": {
                "behat/behat": "^3.0.0",
     “phpunit/phpunit”: “^5.0.0”
     }

•    Next, run composer install command in the terminal.
•    When it is done, you will also notice a new directory bin/ with a Behat file in it. This is the Behat executable and you will use it to run your tests and get debug information.
•    Next, create a file named behat.yml inside the root folder of the project. When Behat runs, it looks for a behat.yml file, which it uses for its 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: ~

Execute the following command to begin setting up the project: 

vendor/bin/behat –init

Within the features folder, this will generate a folder called bootstrap/FeatureContext.php as the default context file.

Writing Stories and Running tests with Behat

Our objective is to summarize the tales in the most compelling manner possible. Under the features/ directory, the narratives are saved with the extension.feature, which indicates that they are written in the human-readable language Gherkin.

Imagine for a moment that you have been tasked with determining whether or not you are able to successfully add material to the Basic page content type on your website. In order to accomplish this, you will need access to the page so that you may fill in the blanks and save the information as an administrator. 

Now, let’s get started on our very first tale:

Feature: Check basic page CT
 In order to create a page
 As an admin
 I want to access /node/add/page
 So that I can create a page

Scenario: Basic Page CT
 Given I am logged in as a user with the "administrator" role
 When I go to "/node/add/page"
 And I enter "Basic page title" for "edit-title-0-value"
 When I press "edit-submit"
 Then I should see "Basic page Basic page title has been created"

The name basic_page.feature is one option for this file. Each feature may contain a number of scenarios, which define the feature’s particular operation in a certain situation. Each scenario will have the following subdivisions: 

  • Given describes the initial condition of the system in great detail.
  • When, which refers to the activity performed by the user
  • Then explains what the user sees once they have performed a certain action.
  • And – in order to preserve the existing link within the scenario. 

The distinctions between “Then,” “And,” and “But” are not particularly significant. These words are provided for your use so that your scenarios will sound more natural and will be easier to read.

Every feature file can be executed using the vendor/bin/behat program. If you wish to run a particular feature file, you need execute the vendor/bin/behat features/basic_page.feature command. In addition to this, a single scenario can be executed by simply adding a line number to the location where the scenario is created, as follows: vendor/bin/behat features/basic_page.feature:11.

There are tools such as vendor/bin/behat -dl and vendor/bin/behat -di that offer the statement syntax along with examples. For example, you can use vendor/bin/behat -dl to obtain all of the statement syntax that is used in scenarios.

How to write Feature files

Behat runs curl requests against URLs on your website, which makes the testing process quite fast, but also makes Behat lose the ability to test features that require Javascript. So, to test features we only need to do add @javascript tag before every scenario that requires Javascript, like this:

Feature: Check basic page CT
 In order to create a page
 As an admin
 I want to access /node/add/page
 So that I can create a page

@api @javascript
Scenario: Basic Page CT
 Given I am logged in as a user with the "administrator" role
 When I go to "/node/add/page"
 And I enter "Basic page title" for "edit-title-0-value"
 And I fill in wysiwyg on field "edit-body-0-value" with "Basic page content"
 When I press "edit-submit"
 Then I should see "Basic page Basic page title has been created"

Execute the vendor/bin/behat file in order to test this. Because each scenario needs to translate to a function, this will display you the stages in the scenario that have not been defined.

test drupal with behat

You have two options: either copy the code snippet and paste it into the FeatureContext.php context file, or you may run the vendor/bin/behat –dry-run –append-snippets command. 

After that, you’ll be able to jot down the definitions for the functions in the FeatureContext.php file as follows:

<?php

use Behat\Mink\Exception\ExpectationException;
use Drupal\DrupalExtension\Context\RawDrupalContext;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends RawDrupalContext {

  /**
   * The mink context.
   *
   * @var Drupal\DrupalExtension\Context\MinkContext
   */
  protected $minkContext;

  /**
   * Initializes context.
   *
   * Every scenario gets its own context instance.
   * You can also pass arbitrary arguments to the
   * context constructor through behat.yml.
   */
  public function __construct() {
  }

  /**
   * Fill in wysiwyg on field.
   *
   * @Then I fill in wysiwyg on field :locator with :value
   */
  public function iFillInWysiwygOnFieldWith($locator, $value) {
    $el = $this->getSession()->getPage()->findField($locator);
    if (empty($el)) {
      throw new ExpectationException('Could not find WYSIWYG with locator: ' . $locator, $this->getSession());
    }
    $fieldId = $el->getAttribute('id');
    if (empty($fieldId)) {
      throw new Exception('Could not find an id for field with locator: ' . $locator);
    }
    $this->getSession()
      ->executeScript("CKEDITOR.instances[\"$fieldId\"].setData(\"$value\");");
  }

}

Now that you’ve done that, execute the command vendor/bin/behat, and every scenario that was written should pass. The JS code that has been defined will act as a map for the scenario statement “And I fill in WYSIWYG on-field “edit-body-0-value” with “Basic page content.”

Conclusion

Now, in the end, we hope that through this post you were able to learn how to test your Drupal website with Behat. However, if you are looking for a Drupal development company, then you should check out Appic Sotwares. We have an experienced team of Drupal developers that will help you with your Drupal requirements.

You can even hire dedicated Drupal developers from us. So what are you waiting for?

Contact us now!

Get Free Consultation Now!


    Contact Us

    Consult us today to develop your application.

      Get in touch with us


      Skype Whatsapp Gmail Phone