SlideShare a Scribd company logo
Introducing

PHPSpec
A BDD Framework
Marcello Duarte
          @_md


PHPSpec Lead Developer
Head of Training @
Agile guy
What is PHPSpec?
 BDD Framework

 Created by Pádraic Brady

 DSL based on RSpec
BDD?
Behaviour Driven Development
BDD?
Better way to explain TDD
TDD?
Write a failing test
TDD?
       Write a failing test

Make it fail for the right reasons
TDD?
      Write a failing test
Make it fail for the right reasons

   Make it pass (just about)
TDD?
      Write a failing test
Make it fail for the right reasons
  Make it pass (just about)

            Refactor
TDD?
      Write a failing test
Make it fail for the right reasons
  Make it pass (just about)
             Refactor

           Start again
Focus on behaviour
Test


Specify
class CalculatorTest


      becomes
class DescribeCalculator
Test Case


Context
class CalculatorTest extends
   SomeTestFramework_TestCase


          becomes
class DescribeCalculator extends
         PHPSpec_Context
Test Method


 Example
testAddWithNoArguments()


         becomes
itReturnsZeroWithNoArguments()
Assert


Expect
$this->assertEquals(0, $result);


         becomes
    $result->should->be(0);
Installing
PEAR (soon...)

# pear channel-discover pear.phpspec.net
Adding Channel "pear.phpspec.net" succeeded
Discovery of channel "pear.phpspec.net" succeeded
# pear install --alldeps phpspec/PHPSpec-beta

GITHUB

$ git clone git://github.com/phpspec/phpspec.git
PHPSpec DSL
# StringCalculatorSpec.php
<?php

class DescribeStringCalculator
  extends PHPSpec_Context {

    public function itReturnsZeroWithNoArguments()
    {
        $result = $this->spec(StringCalculator::add());
        $result->should->be(0);
    }
}
$result->should->be(0)
$result->shouldNot->be(42)
Loads of matchers...
be($match)
         equal($match)
       beEqualTo($match)
    beAnInstanceOf($match)
           beEmpty()
           beFalse()
     beGreaterThan($match)
beGreaterThanOrEqualTo($match)
And more matchers...
beInteger()
    beLessThan($match)
beLessThanOrEqualTo($match)
         beNull()
        beString()
         beTrue()

       coming soon:
  throwException($match)
Predicate Matcher

           $cell = $this->spec(new Cell);
           $cell->should->beAlive();

class Cell
{
    protected $alive = true;

    public function isAlive() {
        return $this->alive;
    }
    ...
}
Predicate Matcher

           $newNode = $this->spec(new Node);
           $newNode->shouldNot->haveChildren();

class Node
{
    protected $children = array();

    public function hasChildren() {
        return count($this->children) > 0;
    }
    ...
}
Lets run our specs
# StringCalculatorSpec.php
<?php

class DescribeStringCalculator
  extends PHPSpec_Context {

    public function itReturnsZeroWithNoArgument()
    {
        $this->spec(StringCalculator::add())->should->be(0);
    }
}
Lets run our specs
$ phpspec StringCalculatorSpec.php -c
.

Finished in 0.055689 seconds

1 examples, 0 failures
Pending examples

public function itReturnsZeroWithAnEmptyString()
{
    $this->pending();
}
$ phpspec StringCalculatorSpec.php -c
.P

Pending:

1)
'string calculator returns zero with an empty
string' PENDING
Incomplete

Finished in 0.056134 seconds

2 examples, 0 failures, 1 pending
$
Failing examples

public function itReturnsTheBareNumber()
{
    $result = $this->spec(StringCalculator::add("42"));
    $result->should->be(42);
}
$ phpspec StringCalculatorSpec.php -c
.PF

Failures:

1)
'string calculator returns the bare number' FAILED
expected 42, got 0 (using be())
/Users/md/BDDTalk/StringCalculatorSpec.php:28

Pending:
...
Finished in 0.056134 seconds

3 examples, 1 failure, 1 pending
$
Deliberate fail

public function itReturnsTheBareNumber()
{
    $this->fail("An optional message");
}
Hooks


 before()
  after()
beforeAll()
afterAll()
set initial state

public function before()
{
    $this->calculator = new StringCalculator();
}
Mocks

               Phake
 https://github.com/mlively/Phake


              Mockery
https://github.com/padraic/Mockery
BDD Outside in
    Gherkin
    Behat

   PHPSpec
Feature: Learners Feedback
  In order to improve the quality of training
  As an learner
  I want to provide feedback for a course

  Scenario: Missed selecting the course
    Given I am on the feedback page
    And I skip selecting the course
    When submit the feedback
    Then I should be warned the feedback was not submitted

  Scenario: Thank you page
    Given I am on the feedback page
    And I fill all fields required
    When submit the feedback
    Then I should see a thank you message
$ pwd
/path/to/my/app
$ ls
features    src   spec
$ behat
PHPSpec BDD Framework
PHPSpec BDD Framework
Goutte


        Screen scraping
  Web crawling library for PHP
Goutte does not start the browser
// Create a Goutte Client
use GoutteClient;

$client = new Client();
// Make requests which returns a Crawler
$crawler = $client->request('GET', 'http://feedbackpage');.

//Click on links:
$link = $crawler->selectLink('Course')->link();
$crawler = $client->click($link);

// Submit forms:
$form = $crawler->selectButton('Submit Feedback')->form();
$crawler = $client->submit($form, array(
    'trainer' => 'Marcello Duarte',
    'course' => 'Agile PHP Developer'));

// Parse results
$error = $crawler->filter('.errors');
The BDD Cycle

         1. Write your stories

       2. Use Gherkin/Behat to
 describe the behaviour of your apps

          3. Use PHPSpec to
describe the behaviour of your classes
Thank you!


    Marcello Duarte
        @_md




is hiring. Come talk to me.

More Related Content

PDF
Clear php reference
KEY
PHPSpec BDD for PHP
PDF
Beginning PHPUnit
PDF
Building Testable PHP Applications
PDF
What's new with PHP7
PDF
PHPunit and you
PDF
PHPUnit Episode iv.iii: Return of the tests
PDF
November Camp - Spec BDD with PHPSpec 2
Clear php reference
PHPSpec BDD for PHP
Beginning PHPUnit
Building Testable PHP Applications
What's new with PHP7
PHPunit and you
PHPUnit Episode iv.iii: Return of the tests
November Camp - Spec BDD with PHPSpec 2

What's hot (19)

PDF
PHP: 4 Design Patterns to Make Better Code
KEY
Intermediate PHP
PDF
Workshop quality assurance for php projects - ZendCon 2013
PDF
TDC2016SP - Trilha Developing for Business
PDF
Developing for Business
PDF
Forget about Index.php and build you applications around HTTP - PHPers Cracow
PDF
UA testing with Selenium and PHPUnit - PFCongres 2013
PPTX
Xenogenetics for PL/SQL - infusing with Java best practices
PDF
PHP Conference Asia 2016
KEY
PHP security audits
PDF
Dependency Injection Smells
ODP
Back to basics - PHP_Codesniffer
PDF
Automated code audits
PDF
Refactoring using Codeception
PPT
Mocking Dependencies in PHPUnit
ODP
Modernising Legacy Code
PDF
Let's Talk Scope
PPT
Oracle PL/SQL - Creative Conditional Compilation
KEY
Workshop quality assurance for php projects tek12
PHP: 4 Design Patterns to Make Better Code
Intermediate PHP
Workshop quality assurance for php projects - ZendCon 2013
TDC2016SP - Trilha Developing for Business
Developing for Business
Forget about Index.php and build you applications around HTTP - PHPers Cracow
UA testing with Selenium and PHPUnit - PFCongres 2013
Xenogenetics for PL/SQL - infusing with Java best practices
PHP Conference Asia 2016
PHP security audits
Dependency Injection Smells
Back to basics - PHP_Codesniffer
Automated code audits
Refactoring using Codeception
Mocking Dependencies in PHPUnit
Modernising Legacy Code
Let's Talk Scope
Oracle PL/SQL - Creative Conditional Compilation
Workshop quality assurance for php projects tek12
Ad

Similar to PHPSpec BDD Framework (20)

PDF
Zend Certification PHP 5 Sample Questions
PDF
関西PHP勉強会 php5.4つまみぐい
PDF
Why is crud a bad idea - focus on real scenarios
KEY
Unit testing zend framework apps
KEY
PHPUnit testing to Zend_Test
KEY
KEY
Unit testing with zend framework PHPBenelux
PDF
Unit testing with zend framework tek11
PPT
Test driven development_for_php
PDF
Phpspec tips&amp;tricks
PDF
Workshop quality assurance for php projects - phpbelfast
KEY
My Development Story
PDF
Ch ch-changes cake php2
PDF
Quality Assurance for PHP projects - ZendCon 2012
PDF
Introduction to Unit Testing with PHPUnit
KEY
Zend Framework Study@Tokyo #2
PDF
PHP 5.3 Overview
KEY
Can't Miss Features of PHP 5.3 and 5.4
PDF
Unit testing after Zend Framework 1.8
PPT
Zend Framework
Zend Certification PHP 5 Sample Questions
関西PHP勉強会 php5.4つまみぐい
Why is crud a bad idea - focus on real scenarios
Unit testing zend framework apps
PHPUnit testing to Zend_Test
Unit testing with zend framework PHPBenelux
Unit testing with zend framework tek11
Test driven development_for_php
Phpspec tips&amp;tricks
Workshop quality assurance for php projects - phpbelfast
My Development Story
Ch ch-changes cake php2
Quality Assurance for PHP projects - ZendCon 2012
Introduction to Unit Testing with PHPUnit
Zend Framework Study@Tokyo #2
PHP 5.3 Overview
Can't Miss Features of PHP 5.3 and 5.4
Unit testing after Zend Framework 1.8
Zend Framework
Ad

More from Marcello Duarte (15)

PDF
Functional Structures in PHP
PDF
Empathy from Agility
PDF
Introducing Eager Design
PDF
Understanding Craftsmanship SwanseaCon2015
PDF
Barely Enough Design
PDF
Transitioning to Agile
PDF
Understanding craftsmanship
PDF
Hexagonal symfony
PDF
The framework as an implementation detail
PDF
PhpSpec 2.0 ilustrated by examples
PDF
Emergent design with phpspec
PDF
Mocking Demystified
PDF
Pair Programming, TDD and other impractical things
PPTX
Deliberate practice
PDF
BDD For Zend Framework With PHPSpec
Functional Structures in PHP
Empathy from Agility
Introducing Eager Design
Understanding Craftsmanship SwanseaCon2015
Barely Enough Design
Transitioning to Agile
Understanding craftsmanship
Hexagonal symfony
The framework as an implementation detail
PhpSpec 2.0 ilustrated by examples
Emergent design with phpspec
Mocking Demystified
Pair Programming, TDD and other impractical things
Deliberate practice
BDD For Zend Framework With PHPSpec

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
cuic standard and advanced reporting.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Programs and apps: productivity, graphics, security and other tools
PPT
Teaching material agriculture food technology
PPTX
Cloud computing and distributed systems.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Empathic Computing: Creating Shared Understanding
Per capita expenditure prediction using model stacking based on satellite ima...
cuic standard and advanced reporting.pdf
Machine learning based COVID-19 study performance prediction
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Programs and apps: productivity, graphics, security and other tools
Teaching material agriculture food technology
Cloud computing and distributed systems.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation theory and applications.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Advanced methodologies resolving dimensionality complications for autism neur...
sap open course for s4hana steps from ECC to s4
Review of recent advances in non-invasive hemoglobin estimation
Spectral efficient network and resource selection model in 5G networks
“AI and Expert System Decision Support & Business Intelligence Systems”
Reach Out and Touch Someone: Haptics and Empathic Computing
Empathic Computing: Creating Shared Understanding

PHPSpec BDD Framework

  • 2. Marcello Duarte @_md PHPSpec Lead Developer Head of Training @ Agile guy
  • 3. What is PHPSpec? BDD Framework Created by Pádraic Brady DSL based on RSpec
  • 5. BDD? Better way to explain TDD
  • 7. TDD? Write a failing test Make it fail for the right reasons
  • 8. TDD? Write a failing test Make it fail for the right reasons Make it pass (just about)
  • 9. TDD? Write a failing test Make it fail for the right reasons Make it pass (just about) Refactor
  • 10. TDD? Write a failing test Make it fail for the right reasons Make it pass (just about) Refactor Start again
  • 13. class CalculatorTest becomes class DescribeCalculator
  • 15. class CalculatorTest extends SomeTestFramework_TestCase becomes class DescribeCalculator extends PHPSpec_Context
  • 17. testAddWithNoArguments() becomes itReturnsZeroWithNoArguments()
  • 19. $this->assertEquals(0, $result); becomes $result->should->be(0);
  • 20. Installing PEAR (soon...) # pear channel-discover pear.phpspec.net Adding Channel "pear.phpspec.net" succeeded Discovery of channel "pear.phpspec.net" succeeded # pear install --alldeps phpspec/PHPSpec-beta GITHUB $ git clone git://github.com/phpspec/phpspec.git
  • 21. PHPSpec DSL # StringCalculatorSpec.php <?php class DescribeStringCalculator extends PHPSpec_Context { public function itReturnsZeroWithNoArguments() { $result = $this->spec(StringCalculator::add()); $result->should->be(0); } }
  • 24. be($match) equal($match) beEqualTo($match) beAnInstanceOf($match) beEmpty() beFalse() beGreaterThan($match) beGreaterThanOrEqualTo($match)
  • 26. beInteger() beLessThan($match) beLessThanOrEqualTo($match) beNull() beString() beTrue() coming soon: throwException($match)
  • 27. Predicate Matcher $cell = $this->spec(new Cell); $cell->should->beAlive(); class Cell { protected $alive = true; public function isAlive() { return $this->alive; } ... }
  • 28. Predicate Matcher $newNode = $this->spec(new Node); $newNode->shouldNot->haveChildren(); class Node { protected $children = array(); public function hasChildren() { return count($this->children) > 0; } ... }
  • 29. Lets run our specs # StringCalculatorSpec.php <?php class DescribeStringCalculator extends PHPSpec_Context { public function itReturnsZeroWithNoArgument() { $this->spec(StringCalculator::add())->should->be(0); } }
  • 30. Lets run our specs $ phpspec StringCalculatorSpec.php -c . Finished in 0.055689 seconds 1 examples, 0 failures
  • 31. Pending examples public function itReturnsZeroWithAnEmptyString() { $this->pending(); }
  • 32. $ phpspec StringCalculatorSpec.php -c .P Pending: 1) 'string calculator returns zero with an empty string' PENDING Incomplete Finished in 0.056134 seconds 2 examples, 0 failures, 1 pending $
  • 33. Failing examples public function itReturnsTheBareNumber() { $result = $this->spec(StringCalculator::add("42")); $result->should->be(42); }
  • 34. $ phpspec StringCalculatorSpec.php -c .PF Failures: 1) 'string calculator returns the bare number' FAILED expected 42, got 0 (using be()) /Users/md/BDDTalk/StringCalculatorSpec.php:28 Pending: ... Finished in 0.056134 seconds 3 examples, 1 failure, 1 pending $
  • 35. Deliberate fail public function itReturnsTheBareNumber() { $this->fail("An optional message"); }
  • 36. Hooks before() after() beforeAll() afterAll()
  • 37. set initial state public function before() { $this->calculator = new StringCalculator(); }
  • 38. Mocks Phake https://github.com/mlively/Phake Mockery https://github.com/padraic/Mockery
  • 39. BDD Outside in Gherkin Behat PHPSpec
  • 40. Feature: Learners Feedback In order to improve the quality of training As an learner I want to provide feedback for a course Scenario: Missed selecting the course Given I am on the feedback page And I skip selecting the course When submit the feedback Then I should be warned the feedback was not submitted Scenario: Thank you page Given I am on the feedback page And I fill all fields required When submit the feedback Then I should see a thank you message
  • 44. Goutte Screen scraping Web crawling library for PHP Goutte does not start the browser
  • 45. // Create a Goutte Client use GoutteClient; $client = new Client(); // Make requests which returns a Crawler $crawler = $client->request('GET', 'http://feedbackpage');. //Click on links: $link = $crawler->selectLink('Course')->link(); $crawler = $client->click($link); // Submit forms: $form = $crawler->selectButton('Submit Feedback')->form(); $crawler = $client->submit($form, array( 'trainer' => 'Marcello Duarte', 'course' => 'Agile PHP Developer')); // Parse results $error = $crawler->filter('.errors');
  • 46. The BDD Cycle 1. Write your stories 2. Use Gherkin/Behat to describe the behaviour of your apps 3. Use PHPSpec to describe the behaviour of your classes
  • 47. Thank you! Marcello Duarte @_md is hiring. Come talk to me.