Quantcast
Channel: Richard Knop
Viewing all articles
Browse latest Browse all 20

Quick Introduction To BDD Testing With Behat

$
0
0

Behat is a PHP framework for BDD testing. It us very similar to Cucumber (RoR) or Behave (Django), it uses Gherkin language to define features and scenarions. These are then executed by Behat, which uses one or several drivers. In this short example I will show you how to use two drivers:

  • Goutte (simple HTTP based headless browser)
  • Selenium 2 (full browser emulator with JS support)

First, let’s use Composer to install Behat and the drivers:

{
    "name": "foo-bar",
    "description": "Foo Bar",
    "minimum-stability": "dev",
    "require": {
        "php": ">=5.3",
    },
    "require-dev": {
        "behat/behat": "dev-develop#1f1bead31e96da5e30fd5d499d5cf66d29b68cf6",
        "behat/mink": "v1.4.3",
        "behat/mink-extension": "dev-master#ef2c8639ebc254f0ff6e555b7834700caf5db9c4",
        "behat/mink-goutte-driver": "dev-master#v1.0.8",
        "behat/mink-selenium2-driver": "v1.0.6",
    }
}

Install the dependencies defined in composer.json file (above):

php composer.phar install --dev

Make sure you have Firefox 21 installed as that’s what we will be using for Selenium 2 tests. Also important, make sure you have Selenium 2 server installed and running. I have written a post explaining how to install Selenium 2 on Mac OS as a service.

This is an example behat.yml file I’m using in one of projects I work on:

default:
  paths:
    features: tests/functional/features
    bootstrap: tests/functional/features/bootstrap
  extensions:
    Behat\MinkExtension\Extension:
      base_url: http://virtualhost.local
      goutte: ~
      default_session: goutte 
      javascript_session: selenium2 
      selenium2: 
        browser: firefox
        capabilities: { "browserName": "firefox", "browser": "firefox", "version": "21"}
        wd_host: http://127.0.0.1:4443/wd/hub

Then you can run the tests like this:

vendor/bin/behat --ansi

All tests with @javascript tag will use Selenium 2 driver (so a new Firefox window will pop up and your tests will run inside it), tests without @javascript tag will run using the headless Goutte driver.

You can exclude Selenium 2 tests like this (for example you might not have an external Selenium 2 server for Jenkins so you might want to run Selenium tests only locally and run only tests without @javascript tag on Jenkins as a part of the build process):

vendor/bin/behat --ansi --tags=~@javascript

Viewing all articles
Browse latest Browse all 20

Trending Articles