Behat PHP: Complete Guide with Examples
1. What Is Behat and Why Use It
Behat is a powerful PHP framework for Behaviour-Driven Development (BDD). It allows you to describe application behavior in plain, almost natural language (Gherkin), then automatically verify that your code matches that description. Behat acts as a bridge between non-technical team members (managers, analysts, clients) and developers, providing a single "living" document that serves as both a specification and a test suite.
Why use Behat? Primarily to improve communication and reduce the risk of misunderstood requirements. Instead of writing technical unit tests that check how a function works, you write scenarios describing what the system should do from the user's perspective. For example, instead of "testLogin()", you write "User enters valid credentials and clicks 'Login'". This makes tests readable for everyone involved. Additionally, Behat is excellent for integration and end-to-end (E2E) testing of web applications, APIs, and console commands.
Behat integrates tightly with Mink — a browser emulation library — allowing you to test web interfaces. However, you can also use it to test pure PHP code without a web context. The core BDD idea implemented in Behat: "First write the scenario, then write the code that makes the scenario pass."
2. Installation
Install Behat via Composer, the standard PHP package manager. Run the following command in your project root:
composer require --dev behat/behat
This installs Behat and all its dependencies into the vendor/ directory and adds an entry to your composer.json file.
If you plan to test web applications, you'll also need Mink and one of its drivers (e.g., Goutte for fast JavaScript-free testing or Selenium2 for real browser testing):
composer require --dev behat/mink-extension behat/mink-goutte-driver behat/mink-selenium2-driver
After installation, initialize Behat in your project:
vendor/bin/behat --init
This creates the directory structure: features/ (for .feature files) and features/bootstrap/ (for the FeatureContext.php class).
3. Quick Start — Minimal Working Example
Create a file called features/hello.feature:
Feature: Hello World
In order to see how Behat works
As a developer
I need to be able to run a simple test
Scenario: Say hello to the user
Given I have a greeting program
When I run it with name "World"
Then I should see "Hello, World!"
Now edit the features/bootstrap/FeatureContext.php file:
greeting = function($name) {
return "Hello, " . $name . "!";
};
}
/**
* @When I run it with name :name
*/
public function iRunItWithName($name)
{
$this->output = call_user_func($this->greeting, $name);
}
}