Introduction
phpspec is a specification-oriented BDD framework for PHP 8.2+. It helps you design clean, well-tested code by describing its behaviour first.
What is Spec BDD?
Spec BDD (Specification Behaviour-Driven Development) is a practice where you describe the behaviour of an object before you write it. Instead of writing tests after the fact, you use a tool like phpspec to express what your code should do, then let that specification drive the implementation.
The value of Spec BDD is not just in verification — it’s in design. By focusing on behaviour rather than implementation, you produce code that is modular, intentional, and easy to change.
Spec BDD vs TDD
Spec BDD and TDD share the red-green-refactor cycle, but they differ in language and intent. TDD talks about “tests” and “assertions”; Spec BDD talks about “examples” and “expectations”.
This shift in vocabulary matters. When you write it('adds two numbers', ...)
instead of testAdd(), you’re describing behaviour, not testing
implementation. The result is specifications that serve as living documentation.
Spec BDD and Story BDD
phpspec 9 unifies Spec BDD and Story BDD in a single tool.
-
Story BDD (Gherkin
.featurefiles) describes system-level behaviour from the user’s perspective: “Given a greeting service, When I greet World, Then I should see Hello, World!” -
Spec BDD (
.spec.phpfiles) describes object-level behaviour from the developer’s perspective: “it adds two numbers”.
Together, they form a complete BDD cycle:
Feature (acceptance) → Steps → Specs (unit) → Classes → Green
What’s new in phpspec 9
phpspec 9 is a complete rewrite. The old ObjectBehavior base
class and Prophecy mocking library are gone, replaced by a modern closure-based DSL.
- Jasmine/RSpec-style syntax —
describe,context,it,let,expect - Built-in mock system —
mock(),allow()->toReturn(),toBeCalled() - Story BDD — Gherkin features with
given/when/thenstep definitions - Minimal dependencies — only
symfony/consoleandsymfony/yaml - Code generation — specs, classes, interfaces, method stubs, step definitions
- AI pair programming —
pair,next,refactorcommands - Parallel execution — Fiber-based worker pool
- Browser testing — built-in HTTP client with response matchers
Requirements
- PHP 8.2, 8.3, 8.4, or 8.5
ext-dom,ext-curl,ext-tokenizer
Installation
$ composer require --dev phpspec/phpspec
That’s it. You’re ready to write your first spec.