Code Generation
phpspec generates specs, classes, interfaces, method stubs, and step definitions to accelerate the spec-first workflow.
The describe command
Generate a spec for a class:
$ bin/phpspec describe App/Calculator
Creates spec/App/Calculator.spec.php with a template:
<?php use App\Calculator; describe(Calculator::class, function() { let("calculator", fn() => new Calculator()); it("instantiates", fn() => expect($this->calculator)->toBeAnInstanceOf(Calculator::class) ); });
With a method example
$ bin/phpspec describe App/Calculator -e add
Generates a spec that includes an example for the add method.
The exemplify command
Add a method example to an existing spec:
$ bin/phpspec exemplify App/Calculator add
If the spec doesn’t exist, it creates one.
Auto-class generation
When specs reference a class that doesn’t exist, phpspec’s custom autoloader prompts:
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] y
Generated class at src/App/Calculator.php:
<?php namespace App; class Calculator { }
Interface generation
When mock() references a class that doesn’t exist, phpspec offers to generate an interface:
Looks like you are trying to mock App\UserRepository, a class that doesn't exist yet. Would you like me to generate that interface for you? [y/n] y
When a mock calls a method that doesn’t exist on the interface, phpspec offers to add it.
Method stub generation
When specs call methods that don’t exist on a class, phpspec generates method stubs:
// Spec calls add() which doesn't exist yet: expect($calc->add(2, 3))->toBe(5);
phpspec generates:
public function add() { }
--fake mode
Go beyond empty stubs — generate method bodies with hardcoded return values from your spec expectations:
$ bin/phpspec run --fake
Given the spec expectation expect($calc->add(2, 3))->toBe(5), phpspec generates:
public function add() { return 5; }
This creates a quick feedback loop: write spec, run with --fake, get passing tests immediately, then replace the faked implementation with real logic.
Step definition generation
When running feature files with undefined steps, phpspec generates step definition stubs. See Features & Steps.
The BDD cycle
phpspec’s code generation creates a natural workflow:
- Write a spec —
bin/phpspec describe App/Calculator - Run specs — phpspec prompts to generate the missing class
- Add examples — write
expect($calc->add(2, 3))->toBe(5) - Run again — phpspec offers to generate the
add()method - Implement — fill in the real logic (or use
--fakefor a quick pass) - Repeat — add more examples, drive the design through specs