Abstracting Behat Web Driver (PHP)

Abstracting Behat Web Driver (PHP)

Behat is an open source Behavior Driven Development framework. It consists of three core Gherkin structures:

  1. Features
  2. Scenarios
  3. Steps/Events

Behat is an awesome tool for writing behaviour driven automated tests. However, a developer may experience a limitation to this framework when writing comphrensive tests on large applications. The Behat framework does not maintain the instance of web driver between scenarios. Making use of Facebook's RemoteWebDriver I created an abstract class that instatiates a web driver.

<?php
use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
abstract class AbstractWebDriver extends \PHPUnit\Framework\TestCase implements Context, SnippetAcceptingContext
{
    /**
     * @var \RemoteWebDriver
     */
    protected static $webDriver;
    protected $baseUrl;
    
    protected function getDriver()
    {
        if($this->webDriver==Null)
            echo "----------------- Instatiate New Driver -----------------";
            $capabilities = DesiredCapabilities::chrome();
            self::$webDriver = RemoteWebDriver::create('http://localhost:4444/wd/hub', $capabilities);
            echo "----------------- Return Current Driver -----------------";
    }
}

A Behat context class extends the AbstractWebDriver class.

<?php
use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Behat\Hook\Scope\BeforeStepScope;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
/**
 * @internal suite::invoicing_improvements
 */
class InvoicingImprovementsContext extends AbstractWebDriver
{
    /**
     * @When I click on about
     */
    public function iClickOnAbout()
    {
        AbstractWebDriver::$webDriver->get("localhost:8080/about");
        AbstractWebDriver::$webDriver->executeScript("$('#about> div > a:nth-child(2) > span').trigger('click')");
    }
}

MIT