Share
Embed
Is TDD dead? A cheeky guide to PhpSpec
A look at PhpSpec and why it could be an alternative to PHP Unit.
Marek Matulka
August 12, 2015
Transcript
68 slides
-
Write a failing scenario (feature) Write a failing test Make
your test pass -
Write a failing scenario (feature) Write a failing test Make
your test pass Refactor your code -
Write a failing scenario (feature) Write a failing test Make
your test pass Refactor your code Repeat the fail-pass-refactor cycle as necessary -
Write a failing scenario (feature) Write a failing test Make
your test pass Refactor your code Make your feature pass -
Write a failing scenario (feature) Write a failing test Make
your test pass Refactor your code Make your feature pass BDD TDD -
Write a failing scenario (feature) Write a failing test Make
your test pass Refactor your code Make your feature pass BDD TDD External Quality Internal Quality -
Starting new project? { "require-dev": { "phpspec/phpspec": "~2.0" }, "config":
{ "bin-dir": "bin" }, "autoload": {"psr-0": {"": "src"}} } -
first spec $ bin/phpspec desc Acme\\StringCalculator Specification for Acme\StringCalculator created
in /home/marek/Workspace/phpsw/spec/Acme/StringCalculatorSpec.php. $ -
first spec $ bin/phpspec desc Acme\\StringCalculator Specification for Acme\StringCalculator created
in /home/marek/Workspace/phpsw/spec/Acme/StringCalculatorSpec.php. $ bin/phpspec run -
first spec $ bin/phpspec run Acme/StringCalculator 10 - it is
initializable class Acme\StringCalculator does not exist. Do you want me to create `Acme\StringCalculator` for you? [Y/n] -
first spec Do you want me to create `Acme\StringCalculator` for
you? [Y/n] Class Acme\StringCalculator created in /home/marek/Workspace/phpsw/src/Acme/StringCalculator.php. 1 specs 1 example (1 passed) 9ms $ -
spec/Acme/StringCalculatorSpec.php <?php namespace spec\Acme; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class StringCalculatorSpec
extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Acme\StringCalculator'); } } -
spec/Acme/StringCalculatorSpec.php class StringCalculatorSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Acme\StringCalculator');
} function it_calculates_empty_string_and_returns_zero() { $this->calculate('')->shouldReturn(0); } } -
$ bin/phpspec run Do you want me to create `Acme\StringCalculator::calculate()`
for you? [Y/n] Method Acme\StringCalculator::calculate() has been created. $ -
$ bin/phpspec run --fake Do you want me to create
`Acme\StringCalculator::calculate()` for you? [Y/n] Method Acme\StringCalculator::calculate() has been created. Do you want me to make `Acme\StringCalculator::calculate()` always return 0 for you? [Y/n] Method Acme\StringCalculator::calculate() has been modified. $ -
$ bin/phpspec run --format pretty Acme\StringCalculator 10 ✔ is initializable
15 ✔ calculates empty string and returns zero 1 specs 2 examples (2 passed) 6ms $ bin/phpspec run -fpretty -
$ bin/phpspec run --format pretty Acme\StringCalculator 10 ✔ is initializable
15 ✔ calculates empty string and returns zero 20 ✔ adds two plus separated integers 25 ✔ adds many plus separated integers 1 specs 4 examples (4 passed) 8ms $ TDD -
class StringCalculator { /** * @param string $input * *
@return integer */ public function calculate($input) { $parts = explode('+', $input); array_walk($parts, function (&$item) { return trim($item); }); return array_sum($parts); } } -
namespace Acme; interface LearnerRepository { /** * @param integer $id
* * @return Learner */ public function findLearnerById($id); } -
use Acme\LearnerRepository; class LearnerDetailsControllerSpec extends ObjectBehaviour { function it_loads_learner(LearnerRepository $repository)
{ $learner = new Learner(); $repository->findLearnerById(5)->willReturn($learner); $this->learnerDetailsAction(5)->shouldReturn($learner); } } -
namespace Acme; interface MessageDispatcher { /** * @param integer $id
* * @return Message */ public function dispatch(Message $message); } -
use Acme\LearnerRepository; use Acme\MessageDispatcher; class LearnerDetailsControllerSpec extends ObjectBehaviour { function
it_loads_learner(LearnerRepository $repository, MessageDispatcher $dispatcher ) { $learner = new Learner(); $repository->findLearnerById(5)->willReturn($learner); $dispatcher->dispatch(Argument::type(Message::class) ->shouldBeCalled(); $this->learnerDetailsAction(5)->shouldReturn($learner); } } -
use Acme\LearnerRepository; use Acme\MessageDispatcher; class LearnerDetailsControllerSpec extends ObjectBehaviour { function
it_loads_learner(LearnerRepository $repository, MessageDispatcher $dispatcher ) { $learner = new Learner(); $repository->findLearnerById(5)->willReturn($learner); $this->learnerDetailsAction(5)->shouldReturn($learner); $dispatcher->dispatch(Argument::type(Message::class) ->shouldHaveBeenCalled(); } } -
use Acme\LearnerRepository; use Acme\MessageDispatcher; class LearnerDetailsControllerSpec extends ObjectBehaviour { function
let( LearnerRepository $repository, MessageDispatcher $dispatcher ) { $this->beConstractedWith($repository, $dispatcher); } function it_loads_learner(LearnerRepository $repository, MessageDispatcher $dispatcher ) { // test... } -
class LearnerSpec extends ObjectBehaviour { function let() { $this->beConstractedThrough( 'fromEmail',
['[email protected]'] ); } function it_can_be_created_with_name() { $this->beConstractedThrough('fromName', ['Test User']); $this->getEmail()->shouldBe(NULL); $this->getName()->shouldReturn('Test User'); } -
Identity Matcher class TrainingAdministratorSpec extends ObjectBehavior { function let() {
$this->beConstructedWith("Test User", "ROLE_COORDINATOR"); } function it_is_a_training_coordinator() { $this->isManager()->shouldBe(false); $this->isCoordinator()->shouldBe(true); $this->getRole()->shouldReturn("ROLE_COORDINATOR"); $this->getName()->shouldBeEqualTo("Test User"); } -
Throw Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_not_allow_empty_name() {
$this->shouldThrow('\InvalidArgumentException') ->during('changeName', ['']); } function it_should_not_allow_empty_name() { $this->shouldThrow(new \InvalidArgumentException()) ->duringChangeName(''); } } -
Throw Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_not_allow_empty_name() {
$this->beConstructedWith(''); $this->shouldThrow('\InvalidArgumentException') ->duringInstantiation(); } } -
Type Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_be_a_training_administrator() {
$this->shouldHaveType(TrainingAdministrator::class); $this->shouldReturnAnInstanceOf(TrainingAdministrator::class); $this->shouldBeAnInstanceOf(TrainingAdministrator::class); $this->shouldImplement(TrainingAdministrator::class); } } -
Object State Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_be_a_training_administrator()
{ $this->isManager()->shouldBe(false); $this->isCoordinator()->shouldBe(true); // calls TrainingAdministrator::isCoordinator() $this->shoudBeCoordinator(); // calls TrainingAdministrator::hasRole() $this->shouldHaveRole('ROLE_COORDINATOR'); } } -
Count Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_have_one_role() {
$this->getRoles()->shouldHaveCount(1); } } -
String Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_have_a_string_as_name() {
$this->beConstructedWith('Test User'); $this->getName()->shouldBeString(); $this->getName()->shouldStartWith('Test'); $this->getName()->shouldEndWith('User'); $this->getName()->shouldMatch('/test/i'); } } -
Array Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_have_an_array_as_roles() {
$this->getRoles()->shouldBeArray(); $this->getRoles()->shouldContain('ROLE_COORDINATOR'); } function it_should_expose_display_data_bag() { $this->toDisplay()->shouldHaveKeyWithValue('name', 'Test User'); $this->toDisplay()->shouldHaveKey('name'); } -
Inline Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_expose_display_data_bag() {
$this->toDisplay()->shouldHaveKey('name'); } function getMatchers() { return [ 'haveKey' => function ($subject, $key) { return array_key_exists($key, $subject); }, ]; } -
why phpspec? - easy to write specs before code -
does (some) code generation for you - helps to stay in the red-green-refactor loop - adds code level documentation - fun to use! -
when not to use phpspec? - functional tests - use
behat or phpunit - integration tests - use phpunit -
how does it fit hexagonal arch? UI Adapter Log Adapter
Data Storage Adapter External Data Adapter Application Domain -
how does it fit hexagonal arch? UI Adapter Log Adapter
Data Storage Adapter External Data Adapter Application Domain -
What to spec? - simple answer: everything! - longer answer:
- everything you can - but don’t use PhpSpec for integration/functional tests - leave it to Behat and/or PHP Unit -
Use fakes for functional tests Fakes are simplified implementations of
your infrastructure / external adapters. - e.g. InMemoryRepository will be a lot faster than Doctrine with mysql when run from inside VM! -
Do test your infrastructure Write integration tests for your repositories
and adapters. Always hide infrastructure / external services behind adapters. -
Want to read more about phpspec? - github.com/phpspec/phpspec - phpspec.net
- groups.google.com/forum/#!forum/phpspec-dev - twitter.com/phpsec