Lesson 42 of 45 · Testing as a Discipline
Behavior-Driven Development
Two things called "BDD"
When someone says they do BDD, they usually mean one of two different things, and the two things have very different costs and benefits.
The first is Dan North's original idea (he started working on it around 2003 and wrote it up in 2006): a refinement of TDD focused on the language and conversations around tests. The tests describe behavior in domain terms, not implementation. The artifact is more readable; the discipline is more communication-shaped.
The second is the tooling that grew up around the idea: Gherkin syntax, Cucumber, Behat. Tests written in Given/When/Then format, often in plain English, parsed by a framework, executed against step definitions. The artifact is documentation that a non-engineer could in principle read.
These are related but not the same. Confusing them produces a lot of bad arguments. This lesson covers both honestly: the lightweight version that needs no tooling, and the heavier tooling version that earns its place in specific contexts.
The original idea
Dan North wrote "Introducing BDD" in 2006 as an attempt to fix problems he saw with how teams talked about TDD. The reframing was small but consequential:
Don't say "test." Say "behavior" or "should." Tests describe what the system should do, not what it tests.
Test names become sentences:
it_should_confirm_reservation_when_payment_is_capturedinstead oftest_confirm_reservation.The conversation about tests becomes a conversation about behavior, which non-engineers can join.
That's the original BDD. It doesn't require any new tooling. PHPUnit supports it directly through method names and #[Test] attributes. The shift is in how you name things and how you think about what you're writing, not in what tools you use.
The tooling-flavored version
The other version of BDD grew up around tools like Cucumber (Ruby) and its PHP equivalent, Behat. It uses Gherkin syntax: tests written in a structured natural language, with Feature, Scenario, Given, When, Then keywords.
Scenarios live in .feature files. This one is features/reservation-pricing.feature:
Feature: Reservation pricing
In order to charge correctly
As a guest
I want my reservation to apply applicable discounts
Scenario: Weekly discount applies for 7+ night stays
Given a room with a nightly rate of 50 dollars
And a rate plan with a 20 percent weekly discount
When I reserve the room for 30 nights
Then the price should be 1200 dollars
Scenario: Stays shorter than a week pay the full rate
Given a room with a nightly rate of 50 dollars
And a rate plan with a 20 percent weekly discount
When I reserve the room for 3 nights
Then the price should be 150 dollarsThe English-looking sentences map to step definitions (PHP code) that exercise the system. The example targets Behat 4.0, released in September 2026, which defines steps with PHP attributes. Behat 4.0 removed the older docblock annotations (@Given). The scenarios exercise LongStayPricing, the class that prices a stay:
<?php
declare(strict_types=1);
namespace App\Pricing;
use App\Billing\Currency;
use App\Billing\ExchangeRates;
use App\Billing\Money;
use App\Booking\Room;
use App\Reservations\DateRange;
use Psr\Clock\ClockInterface as Clock;
final readonly class LongStayPricing
{
public function __construct(
private ExchangeRates $exchangeRates,
private Clock $clock,
) {}
public function quote(Room $room, RatePlan $ratePlan, DateRange $stayDates, Currency $billingCurrency): Money
{
$nights = $stayDates->nights();
$base = $room->nightlyRate->multiplyBy($nights);
if ($nights >= 7 && $ratePlan->weeklyDiscountPercent > 0) {
$base = $base->applyDiscountPercent($ratePlan->weeklyDiscountPercent);
}
if ($ratePlan->isPromotionalAt($this->clock->now())) {
$base = $base->applyDiscountPercent($ratePlan->promoDiscountPercent);
}
return $this->exchangeRates->convert($base, $billingCurrency);
}
}ExchangeRates is the interface from the test doubles lesson. Room and RatePlan are trimmed for this lesson to the fields the calculator reads. Room holds the nightly rate:
<?php
declare(strict_types=1);
namespace App\Booking;
use App\Billing\Money;
final readonly class Room
{
public function __construct(public Money $nightlyRate) {}
}RatePlan holds a weekly discount percent, a promo discount percent and a promo window, and isPromotionalAt() says whether a given moment falls inside that window:
<?php
declare(strict_types=1);
namespace App\Pricing;
use DateTimeImmutable;
final readonly class RatePlan
{
public function __construct(
public int $weeklyDiscountPercent,
public int $promoDiscountPercent,
private ?DateTimeImmutable $promoStartsAt,
private ?DateTimeImmutable $promoEndsAt,
) {}
public function isPromotionalAt(DateTimeImmutable $moment): bool
{
return $this->promoStartsAt !== null
&& $this->promoEndsAt !== null
&& $moment >= $this->promoStartsAt
&& $moment < $this->promoEndsAt;
}
}RoomBuilder and RatePlanBuilder are test data builders in the shape of the test doubles lesson's ReservationBuilder: new(), with...() methods that return a changed clone, and build(). They set only what these tests vary, and default everything else:
<?php
declare(strict_types=1);
namespace App\Testing;
use App\Billing\Currency;
use App\Billing\Money;
use App\Booking\Room;
final class RoomBuilder
{
private Money $nightlyRate;
private function __construct()
{
$this->nightlyRate = Money::fromDollars(100.00, Currency::usd());
}
public static function new(): self
{
return new self();
}
public function withNightlyRate(Money $nightlyRate): self
{
$clone = clone $this;
$clone->nightlyRate = $nightlyRate;
return $clone;
}
public function build(): Room
{
return new Room($this->nightlyRate);
}
}<?php
declare(strict_types=1);
namespace App\Testing;
use App\Pricing\RatePlan;
final class RatePlanBuilder
{
private int $weeklyDiscountPercent = 0;
private function __construct() {}
public static function new(): self
{
return new self();
}
public function withWeeklyDiscountPercent(int $percent): self
{
$clone = clone $this;
$clone->weeklyDiscountPercent = $percent;
return $clone;
}
public function build(): RatePlan
{
return new RatePlan(
weeklyDiscountPercent: $this->weeklyDiscountPercent,
promoDiscountPercent: 0,
promoStartsAt: null,
promoEndsAt: null,
);
}
}The context builds the calculator itself, with an ExchangeRates that returns the amount unchanged, and fails a step by throwing:
<?php
declare(strict_types=1);
namespace Tests\Pricing\Behat;
use App\Billing\Currency;
use App\Billing\ExchangeRates;
use App\Billing\Money;
use App\Booking\Room;
use App\Pricing\LongStayPricing;
use App\Pricing\RatePlan;
use App\Reservations\DateRange;
use App\Testing\FrozenClock;
use App\Testing\RatePlanBuilder;
use App\Testing\RoomBuilder;
use Behat\Behat\Context\Context;
use Behat\Step\Given;
use Behat\Step\Then;
use Behat\Step\When;
use Carbon\CarbonImmutable;
use RuntimeException;
final class ReservationPricingContext implements Context
{
private Room $room;
private RatePlan $ratePlan;
private Money $price;
private LongStayPricing $pricing;
public function __construct()
{
$this->pricing = new LongStayPricing(
new class implements ExchangeRates {
public function convert(Money $amount, Currency $to): Money
{
return $amount;
}
},
new FrozenClock('2026-05-01'),
);
}
#[Given('a room with a nightly rate of :dollars dollars')]
public function aRoomWithNightlyRate(float $dollars): void
{
$this->room = RoomBuilder::new()
->withNightlyRate(Money::fromDollars($dollars, Currency::usd()))
->build();
}
#[Given('a rate plan with a :percent percent weekly discount')]
public function aRatePlanWithWeeklyDiscount(int $percent): void
{
$this->ratePlan = RatePlanBuilder::new()->withWeeklyDiscountPercent($percent)->build();
}
#[When('I reserve the room for :nights nights')]
public function iReserveTheRoom(int $nights): void
{
$checkIn = CarbonImmutable::parse('2026-06-01');
$this->price = $this->pricing->quote(
$this->room,
$this->ratePlan,
DateRange::ofNights($checkIn, $nights),
Currency::usd(),
);
}
#[Then('the price should be :dollars dollars')]
public function thePriceShouldBe(float $dollars): void
{
$expected = Money::fromDollars($dollars, Currency::usd());
if (! $expected->equals($this->price)) {
throw new RuntimeException(sprintf(
'Expected %s but the price was %s.',
$expected->format(),
$this->price->format(),
));
}
}
}Behat 4 reads its configuration from behat.php in the project root. It dropped YAML configuration, so a behat.yml from older tutorials is not read. The file registers one suite that points at the features directory and the context class:
<?php
declare(strict_types=1);
use Behat\Config\Config;
use Behat\Config\Profile;
use Behat\Config\Suite;
use Tests\Pricing\Behat\ReservationPricingContext;
return (new Config())
->withProfile(
(new Profile('default'))
->withSuite(
(new Suite('pricing'))
->withPaths('%paths.base%/features')
->withContexts(ReservationPricingContext::class),
),
);Install Behat with composer require --dev behat/behat:^4.0. The context class relies on Laravel's default Tests\ mapping in autoload-dev, so Composer can find it. Then vendor/bin/behat runs both scenarios.
The promise: the scenarios are readable by non-engineers (product managers, business analysts, customers). The conversation about what the system should do happens in the same artifact that runs as a test.
The reality, in the codebases I've worked on: the scenarios get written by engineers, read mostly by engineers, and the maintenance overhead of step definitions outweighs the cross-team readability benefit. The tooling earns its place in some contexts and doesn't in others.
Given-When-Then as a structure
Whether or not you use the tooling, the Given/When/Then framing is useful as a way to structure tests:
Given. The setup. The state of the world before the action under test.
When. The action. The thing being tested.
Then. The expected outcome. What should be true after the action.
A PHPUnit test written in that shape:
<?php
declare(strict_types=1);
namespace Tests\Pricing;
use App\Billing\Currency;
use App\Billing\ExchangeRates;
use App\Billing\Money;
use App\Pricing\LongStayPricing;
use App\Pricing\RatePlan;
use App\Reservations\DateRange;
use App\Testing\FrozenClock;
use App\Testing\RatePlanBuilder;
use App\Testing\RoomBuilder;
use Carbon\CarbonImmutable;
use PHPUnit\Framework\TestCase;
final class ReservationPricingTest extends TestCase
{
private LongStayPricing $pricing;
private RatePlan $standardRatePlan;
protected function setUp(): void
{
$exchangeRates = $this->createStub(ExchangeRates::class);
$exchangeRates->method('convert')->willReturnArgument(0);
$this->pricing = new LongStayPricing($exchangeRates, new FrozenClock('2026-05-01'));
$this->standardRatePlan = RatePlanBuilder::new()->withWeeklyDiscountPercent(20)->build();
}
public function test_weekly_discount_applies_for_long_stays(): void
{
// Given
$room = RoomBuilder::new()
->withNightlyRate(Money::fromDollars(50.00, Currency::usd()))
->build();
$checkIn = CarbonImmutable::parse('2026-06-01');
// When
$price = $this->pricing->quote(
$room,
$this->standardRatePlan,
DateRange::ofNights($checkIn, 30),
Currency::usd(),
);
// Then
$this->assertEquals(
Money::fromDollars(1200.00, Currency::usd()),
$price,
);
}
}It has the same shape as Gherkin without the tooling, and reads as a small story: the world was like this, then this happened, then this should be true.
When the heavy tooling earns its place
Behat (or similar) earns its place when:
Non-engineers genuinely read and write the scenarios. Some teams have product or QA people who maintain Gherkin scenarios alongside engineers. The cross-role authoring is real, the documentation value is real, and the tooling pays back.
The product is heavily compliance- or contract-driven. Insurance, finance, healthcare. Domains where "this scenario must produce this outcome" is a contract with auditors or regulators. Gherkin scenarios as living specifications are valuable.
The team is large enough that documentation drift is a real problem and the structured language helps keep the spec and the code in sync.
Step definitions can be reused across many scenarios. The overhead of writing a step definition pays back when twenty scenarios share it.
It doesn't earn its place when:
Only engineers ever read or write the scenarios. You've taken on the cost of Gherkin syntax with no cross-role benefit.
The team is small and the in-code test names already do the documentation job.
The scenarios are mostly translation layers for tests that would have been clearer as plain PHPUnit. Writing a step definition that just calls a class method is overhead with no payoff.
The framework's natural test style is already readable. A PHPUnit test method named
it_applies_a_weekly_discount_for_long_staysalready reads like a behavior statement.
The PHP landscape
PHPUnit with #[Test] attributes. Group related behaviors in a single test class and name each method after the behavior it asserts. The #[Test] attribute frees you from the test_ prefix and lets the method read as a sentence. This class covers the case the Given-When-Then test above leaves out, a stay shorter than a week, and drops the // Given, // When, // Then comments because the test reads clearly without them:
<?php
declare(strict_types=1);
namespace Tests\Pricing;
use App\Billing\Currency;
use App\Billing\ExchangeRates;
use App\Billing\Money;
use App\Pricing\LongStayPricing;
use App\Reservations\DateRange;
use App\Testing\FrozenClock;
use App\Testing\RatePlanBuilder;
use App\Testing\RoomBuilder;
use Carbon\CarbonImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class ReservationPricingScenariosTest extends TestCase
{
#[Test]
public function it_charges_the_full_rate_for_stays_shorter_than_a_week(): void
{
$exchangeRates = $this->createStub(ExchangeRates::class);
$exchangeRates->method('convert')->willReturnArgument(0);
$pricing = new LongStayPricing($exchangeRates, new FrozenClock('2026-05-01'));
$room = RoomBuilder::new()
->withNightlyRate(Money::fromDollars(50.00, Currency::usd()))
->build();
$ratePlan = RatePlanBuilder::new()->withWeeklyDiscountPercent(20)->build();
$price = $pricing->quote(
$room,
$ratePlan,
DateRange::ofNights(CarbonImmutable::parse('2026-06-01'), 3),
Currency::usd(),
);
$this->assertEquals(Money::fromDollars(150.00, Currency::usd()), $price);
}
}The class name groups the feature and each method is a scenario. A second scenario goes in as another method in the same class.
Behat. If your team has the cross-role authoring story to justify the overhead, it's a solid tool. "BDD is best practice" is not a reason to adopt it.
Symfony. The friends-of-behat/symfony-extension package runs Behat against the Symfony kernel so contexts can receive services from the container. Version 2.7.0 on Packagist requires symfony/http-kernel ^7.4 || ^8.0 and behat/behat ^3.31 || ^4.0. For the clock, Symfony ships Symfony\Component\Clock\MockClock, which implements the PSR clock interface like FrozenClock does, so new MockClock('2026-05-01') can replace new FrozenClock('2026-05-01') in the examples above.
Pitfalls
Confusing the two BDDs. Saying "we don't do BDD" when you mean "we don't use Behat", or "we do BDD" when you just mean "we name our tests well", produces meaningless arguments. Be specific about which version you mean.
Gherkin nobody reads. Scenarios only engineers maintain cost the language with no cross-role benefit.
Overly clever step definitions. A step like Given a reservation in the system that does ten lines of setup is hiding the test's behavior in the step definition file. The reader of the scenario doesn't know what "in the system" means, and the step definitions become their own undocumented language.
Step explosion. A codebase where most step definitions are used by one or two scenarios hasn't gotten the reuse benefit Gherkin promises. The investment was the cost; the payoff didn't arrive.
Letting BDD-flavored names hide bad tests. A test named it_should_correctly_handle_the_case is named in BDD style and tells you nothing. The naming convention is a tool for clarity, not a substitute for thinking about what the test is checking.
The one thing to remember
BDD is two things sharing a name. The lightweight version is "name your tests after behavior, in domain language" and applies to almost every test you'll ever write. The heavyweight version is Gherkin tooling, and it earns its place when non-engineers genuinely participate in the scenarios.
Related Links
- Introducing BDDDan North's original 2006 article that started BDD, the source of the "behavior not test" reframing this lesson opens with.
- Behat DocumentationThe official docs for the PHP tool that runs Gherkin scenarios, covered in this lesson's tooling-flavored section.
- GherkinThe reference for the Given/When/Then syntax used in this lesson's Feature file example.
- PHPUnit ManualThe official docs for the #[Test] attribute this lesson uses to write behavior-named test methods.