Getting Started
Requirements
- PHP 8.3 or higher
- Composer
Installation
$ composer require phpspec/phpspec --dev
Your First Spec
Generate a spec for a class:
$ vendor/bin/phpspec describe App/Calculator
This creates spec/App/Calculator.spec.php:
<?php use App\Calculator; describe(Calculator::class, function() { this("calculator", fn() => new Calculator()); it("instantiates", fn() => expect($this->calculator)->toBeAnInstanceOf(Calculator::class)); });
Running Specs
Run all specs (from the spec/ directory by default):
$ vendor/bin/phpspec run
Run a specific spec file:
$ vendor/bin/phpspec run spec/App/Calculator.spec.php
Run specs from a specific directory:
$ vendor/bin/phpspec run spec/App/Console
The Spec File Convention
Spec files must end with .spec.php. The loader recursively scans the spec/ directory for all files matching this pattern.
Auto-Class Generation
When a spec describes a class that doesn't exist, the run says so where the error would have been, and offers the class:
Looks like you are trying to spec App\Calculator, a class that doesn't exist yet. Would you like me to generate that class for you? [Y/n]
Pressing Enter generates the class in src/ following the namespace structure, and names the file it wrote. Run again and the spec runs against it.
Story BDD
PhpSpec also supports Gherkin-style feature files. Create .feature files in a features/ directory:
Feature: Calculator Scenario: Adding numbers Given a calculator When I add 2 and 3 Then the result should be 5
Define steps in features/steps/steps.php (or any *.steps.php there) and run with:
$ vendor/bin/phpspec run features/
See Story BDD for full details.
Code Coverage
Generate a coverage report:
$ vendor/bin/phpspec run --coverage
Or an HTML report:
$ vendor/bin/phpspec run --coverage-html coverage/
Requires PCOV enabled, or Xdebug in coverage mode (xdebug.mode=coverage).
Next Steps
- Writing Specs: DSL functions, hooks, pending/focused
- Matchers: All 30+ available matchers
- Mocking: Test doubles with
mock()andallow() - CLI Reference: All commands and options
- Configuration:
phpspec.jsonreference