Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Is TDD dead? A cheeky guide to PhpSpec

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
Tweet

More Decks by Marek Matulka

Other Decks in Programming

Transcript

  1. Write a failing scenario (feature) Write a failing test Make

    your test pass Refactor your code Repeat the fail-pass-refactor cycle as necessary
  2. Write a failing scenario (feature) Write a failing test Make

    your test pass Refactor your code Make your feature pass
  3. Write a failing scenario (feature) Write a failing test Make

    your test pass Refactor your code Make your feature pass BDD TDD
  4. 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
  5. Starting new project? { "require-dev": { "phpspec/phpspec": "~2.0" }, "config":

    { "bin-dir": "bin" }, "autoload": {"psr-0": {"": "src"}} }
  6. first spec $ bin/phpspec desc Acme\\StringCalculator Specification for Acme\StringCalculator created

    in /home/marek/Workspace/phpsw/spec/Acme/StringCalculatorSpec.php. $
  7. first spec $ bin/phpspec desc Acme\\StringCalculator Specification for Acme\StringCalculator created

    in /home/marek/Workspace/phpsw/spec/Acme/StringCalculatorSpec.php. $ bin/phpspec run
  8. 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]
  9. 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 $
  10. 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'); } }
  11. $ bin/phpspec run Do you want me to create `Acme\StringCalculator::calculate()`

    for you? [Y/n] Method Acme\StringCalculator::calculate() has been created. $
  12. $ 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. $
  13. $ 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
  14. $ 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
  15. 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); } }
  16. namespace Acme; interface LearnerRepository { /** * @param integer $id

    * * @return Learner */ public function findLearnerById($id); }
  17. 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); } }
  18. namespace Acme; interface MessageDispatcher { /** * @param integer $id

    * * @return Message */ public function dispatch(Message $message); }
  19. 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); } }
  20. spy

  21. 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(); } }
  22. 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... }
  23. 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'); }
  24. 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"); }
  25. 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(''); } }
  26. Throw Matcher class TrainingAdministratorSpec extends ObjectBehavior { function it_should_not_allow_empty_name() {

    $this->beConstructedWith(''); $this->shouldThrow('\InvalidArgumentException') ->duringInstantiation(); } }
  27. 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); } }
  28. 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'); } }
  29. 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'); } }
  30. 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'); }
  31. 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); }, ]; }
  32. 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!
  33. when not to use phpspec? - functional tests - use

    behat or phpunit - integration tests - use phpunit
  34. how does it fit hexagonal arch? UI Adapter Log Adapter

    Data Storage Adapter External Data Adapter Application Domain
  35. how does it fit hexagonal arch? UI Adapter Log Adapter

    Data Storage Adapter External Data Adapter Application Domain
  36. 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
  37. 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!
  38. Do test your infrastructure Write integration tests for your repositories

    and adapters. Always hide infrastructure / external services behind adapters.
  39. Want to read more about phpspec? - github.com/phpspec/phpspec - phpspec.net

    - groups.google.com/forum/#!forum/phpspec-dev - twitter.com/phpsec