SlideShare ist ein Scribd-Unternehmen logo
1 von 76
PHPSpec
 BDD for PHP
Marcello Duarte
          @_md


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

 Created by Pádraic Brady
What is PHPSpec?
 BDD Framework

 Created by Pádraic Brady

 DSL based on RSpec
BDD?
Better way to explain TDD
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
Unit Testing
XP: test everything that can possibly break
Unit Testing
XP: test everything that can possibly break
       Unit: vague and structural 1:1
Unit Testing
XP: test everything that can possibly break
       Unit: vague and structural 1:1
       Focus on code not behaviour
It’s all in the mind
 It’s soo simple, it does not need tests
It’s all in the mind
 It’s soo simple, it does not need tests
      I’ve done this millions of times
It’s all in the mind
      It’s soo simple, it does not need tests
           I’ve done this millions of times
I will write my code rst and test if I have time
Focus on value
Focus on behaviour
Test
Test
Test


Specify
class CalculatorTest


      becomes
class DescribeCalculator
Test Case
Test Case
Test Case


Context
class CalculatorTest extends
   SomeTestFramework_TestCase


          becomes
class DescribeCalculator extends
        PHPSpecContext
Test Method
Test Method
Test Method


 Example
testAddWithNoArguments()


         becomes
itReturnsZeroWithNoArguments()
Assert
Assert
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 config-set preferred_state beta
# pear install --alldeps phpspec/PHPSpec

GITHUB

$ git clone git://github.com/phpspec/phpspec.git
Set initial state
# StringCalculatorSpec.php
<?php


class DescribeStringCalculator extends PHPSpecContext
{
    function before()
    {
        $this->calculator = $this->spec(new StringCalculator);
    }
}
PHPSpec DSL

class DescribeStringCalculator extends PHPSpecContext
{
    ...

    function itReturnsZeroWithNoArguments()
    {
        $this->calculator->add()->should->be(0);
    }
}
Lets run our specs
$ phpspec StringCalculatorSpec.php -c
..

Finished in 0.055689 seconds

2 examples, 0 failures
Pending examples

function itReturnsTheBareNumber()
{
    $this->pending('Waiting to clarify the spec');
}
$ phpspec StringCalculatorSpec.php -c
..*

Pending:
  String Calculator returns the bare number
     # Waiting to clarify the spec
     # ./spec/StringCalculatorSpec.php:19

Finished in 0.056134 seconds
2 examples, 0 failures, 1 pending
$
Failing examples

public function itReturnsTheSumOfSpaceSeparatedString()
{
    $this->calculator->add('4 2')->should->be(6);
}

// this will fail because it’s not yet implemented
$ phpspec StringCalculatorSpec.php -c
.*.F

Pending:
  String Calculator returns the bare number
     # Waiting to clarify the spec
     # ./spec/StringCalculatorSpec.php:19

Failures:
  1) String Calculator returns the sum of space separate string
     expected 6, got NULL (using be())
     # .spec/StringCalculatorSpec.php:28

Finished in 0.056134 seconds
4 examples, 1 failure, 1 pending
$
$result->should->be(0)
$result->shouldNot->be(42)
$ phpspec StringCalculatorSpec.php -c
.*.F

Pending:
  String Calculator returns the bare number
     # Waiting to clarify the spec
     # ./spec/StringCalculatorSpec.php:19

Failures:
  1) String Calculator returns the sum of space separate string
     expected 42, not to be 24 (using be())
     # .spec/StringCalculatorSpec.php:28

Finished in 0.056134 seconds
4 examples, 1 failure, 1 pending
$
Deliberate fail

public function itReturnsTheBareNumber()
{
    $this->fail('Just because');
}
$ phpspec StringCalculatorSpec.php -c
.*.F

Pending:
  String Calculator returns the bare number
     # Waiting to clarify the spec
     # ./spec/StringCalculatorSpec.php:19

Failures:
  1) String Calculator returns the sum of space separate string
     expected 42, got 0 (using be())
     # .spec/StringCalculatorSpec.php:28

  2) StringCalculator returns the sum of any white space
separated string
     Failure/Error:
     Just because

Finished in 0.056134 seconds
4 examples, 1 failure, 1 pending
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()

  throwException($match)
beInteger()
     beLessThan($match)
beLessThanOrEqualTo($match)
           beNull()
          beString()
           beTrue()

                           w
  throwException($match) ne
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;
    }
    ...
}
User De ned Matcher
class DescribeRapture extends PHPSpecContext
{
   ...
    function itIsNotTheEndOfTheWorldAsWeKnowIt()
    {
        $today = new DateTime('2011-05-20');
        $this->rapture->setDate($today)
        $this->rapture->shouldNot->happenToday();
    }
}
$ phpspec RaptureSpec.php -c
E

Exceptions:
  1) Rapture is not the end of the world as we know it
     Failure/Error: $this->rapture->shouldNot->happenToday();
     PHPSpecException: unknown method call
     # ./RaptureSpec.php:19
     # /usr/share/pear/PHPSpec/Runner/Example.php:168

Finished in 0.056134 seconds
1 examples, 1 exception
$
PHPSpecMatcherdefine('happenToday', function() {
    return array (
        'match' => function($rapture) {
            return $rapture->happensToday();
        },
        'failure_message_for_should_not' =>
            function($rapture) {
                return sprintf("expected %s not to mean kaput",
                       $rapture->getDate());
            }
    );
});

class DescribeRapture extends PHPSpecContext
{   ...
    function itIsNotTheEndOfTheWorldAsWeKnowIt() {
        $today = new DateTime('2011-05-20');
        $this->rapture->setDate($today)
        $this->rapture->shouldNot->happenToday();
    }
}
http://farm5.static.flickr.com/4140/4926597784_4392361eb6_b_d.jpg
PHPSpecMatcherdefine('contain', function($course) {
    return array (
        'match' => function($repository) use ($course) {
            return $repository->has($course);
        },
        'failure_message_for_should' =>
            function($repository) use ($course) {
                return "expected $course to be in repository";
            }
    );
});

class DescribeCourseRepository extends PHPSpecContext
{   ...
    function itAddsNewCourses() {
        $course = new Course("BDD with PHPSpec");
        $this->courses->add($course);
        $this->courses->should->contain(course);
    }
}
$ phpspec CourseRepositorySpec.php -c
F

Failures:
  1) Course Repository adds new courses
     Failure/Error: $this->courses->should->contain(course);
     expected 'BDD with PHPSpec' to be in repository
     # ./CourseRepository.php:19

Finished in 0.056134 seconds
1 examples, 1 failure
$
Hooks


  before()
   after()
beforeAll()
 afterAll()
Mocks
Mocks


 mock()
 stub()
double()
Stub Example
$greeter = stub('Greeter');
$greeter->stub('greet')->andReturn('Hello Mocks!');

$hello = $this->spec(new HelloWorld($greeter));
$hello->sayHello()->should->equal('Hello Mocks!');
Partial Stub
$greeter = mock('Greeter');
$greeter ->stub('greet')
         ->shouldReceive('Chuck')
         ->andReturn('Hello Chuck!');

$hello = $this->spec(new HelloWorld($greeter));
$hello->sayHello()->should->equal('Hello Chuck!');
Shortcut
$greeter = stub('Greeter', array('greet' => 'Hello World!'));

$hello = $this->spec(new HelloWorld($greeter));
$hello->sayHello()->should->equal('Hello World!');
Mocks and hinted type
class HelloWorld
{
    public function __construct(Greeter $greeter) // <-- type
    {
        ...
    }
}

$greeter = mock('Greeter'); // <-- we are covered
Empty doubles
class HelloWorld
{
    public function __construct($greeter) // <-- no type
    {
        ...
    }
}

$greeter = mock(); // <-- no need for types
Counters
$greeter ->stub('greet')->andReturn('Hello Chuck!')
         ->exactly(42);

$greeter ->stub('greet')->andReturn('Hello Chuck!')
         ->never();
Coming soon (more counters)
$greeter ->stub('greet')->andReturn('Hello Chuck!')
         ->atLeast(2);

$greeter ->stub('greet')->andReturn('Hello Chuck!')
         ->atMost(5);

$greeter ->stub('greet')->andReturn('Hello Chuck!')
         ->between('2..5');
Coming soon (stub chain)
                        Instead of

$frontController = double();
$dispatcher       = double();
$route            = double();
$request          = double();
$request->stub('frontController')
         ->andReturn($frontController);
$frontController->stub('dispatcher')->andReturn($dispatcher);
$dispatcher->stub('route')->andReturn($route);
$route->stub('request')->andReturn($request);
Coming soon (stub chain)
                      You can have

$request->stubChain('frontController', 'dispatcher', 'route',
'request');
More to come

      CI friendly reports
      functional approach
           backtrace
             fail fast
            autorun
      run single examples
integration with ZF and Kohana
Links
 http://github.com/phpspec/phpspec
http://github/phpspec/phpspec-mocks
        http://www.phpspec.net

http://dannorth.net/introducing-bdd

       http://twitter.com/_md
     http://twitter.com/phpspec
Thank you!

       Marcello Duarte
           @_md

http://joind.in/talk/view/3469




   is hiring. Come talk to me.

Weitere ähnliche Inhalte

Was ist angesagt?

Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
Jay Shirley
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
Lin Yo-An
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
PrinceGuru MS
 

Was ist angesagt? (20)

Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016
 
PHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the testsPHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the tests
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning C
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
New in php 7
New in php 7New in php 7
New in php 7
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Dependency Injection in PHP
Dependency Injection in PHPDependency Injection in PHP
Dependency Injection in PHP
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 

Andere mochten auch

Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
Joshua Warren
 
S3 Overview Presentation
S3 Overview PresentationS3 Overview Presentation
S3 Overview Presentation
bcburchn
 

Andere mochten auch (20)

Emergent design with phpspec
Emergent design with phpspecEmergent design with phpspec
Emergent design with phpspec
 
(Have a) rest with Laravel
(Have a) rest with Laravel(Have a) rest with Laravel
(Have a) rest with Laravel
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
 
Hexagonal symfony
Hexagonal symfonyHexagonal symfony
Hexagonal symfony
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Windows Azure Platform
Windows Azure PlatformWindows Azure Platform
Windows Azure Platform
 
Commit University - Microsoft Azure
Commit University - Microsoft AzureCommit University - Microsoft Azure
Commit University - Microsoft Azure
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
 
Software Testing & PHPSpec
Software Testing & PHPSpecSoftware Testing & PHPSpec
Software Testing & PHPSpec
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University - Exploring Angular 2
Commit University - Exploring Angular 2
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpec
 
Machine learning in php php con poland
Machine learning in php   php con polandMachine learning in php   php con poland
Machine learning in php php con poland
 
Machine learning in php
Machine learning in phpMachine learning in php
Machine learning in php
 
S3 Overview Presentation
S3 Overview PresentationS3 Overview Presentation
S3 Overview Presentation
 
Reactive Laravel - Laravel meetup Groningen
Reactive Laravel - Laravel meetup GroningenReactive Laravel - Laravel meetup Groningen
Reactive Laravel - Laravel meetup Groningen
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
Hunt for dead code
Hunt for dead codeHunt for dead code
Hunt for dead code
 
Php 7.2 compliance workshop php benelux
Php 7.2 compliance workshop php beneluxPhp 7.2 compliance workshop php benelux
Php 7.2 compliance workshop php benelux
 
php & performance
 php & performance php & performance
php & performance
 

Ähnlich wie PHPSpec BDD for PHP

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 

Ähnlich wie PHPSpec BDD for PHP (20)

PHPSpec BDD Framework
PHPSpec BDD FrameworkPHPSpec BDD Framework
PHPSpec BDD Framework
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Zend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsZend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample Questions
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
PHP 5.4
PHP 5.4PHP 5.4
PHP 5.4
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
My Development Story
My Development StoryMy Development Story
My Development Story
 
Smelling your code
Smelling your codeSmelling your code
Smelling your code
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 

Mehr von Marcello Duarte

Mehr von Marcello Duarte (11)

Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHP
 
Empathy from Agility
Empathy from AgilityEmpathy from Agility
Empathy from Agility
 
Introducing Eager Design
Introducing Eager DesignIntroducing Eager Design
Introducing Eager Design
 
Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015
 
Barely Enough Design
Barely Enough DesignBarely Enough Design
Barely Enough Design
 
Transitioning to Agile
Transitioning to AgileTransitioning to Agile
Transitioning to Agile
 
Understanding craftsmanship
Understanding craftsmanshipUnderstanding craftsmanship
Understanding craftsmanship
 
The framework as an implementation detail
The framework as an implementation detailThe framework as an implementation detail
The framework as an implementation detail
 
Pair Programming, TDD and other impractical things
Pair Programming, TDD and other impractical thingsPair Programming, TDD and other impractical things
Pair Programming, TDD and other impractical things
 
Deliberate practice
Deliberate practiceDeliberate practice
Deliberate practice
 
BDD For Zend Framework With PHPSpec
BDD For Zend Framework With PHPSpecBDD For Zend Framework With PHPSpec
BDD For Zend Framework With PHPSpec
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

PHPSpec BDD for PHP

  • 2. Marcello Duarte @_md PHPSpec Lead Developer Head of Training @ Agile guy
  • 4. What is PHPSpec? BDD Framework
  • 5. What is PHPSpec? BDD Framework Created by Pádraic Brady
  • 6. What is PHPSpec? BDD Framework Created by Pádraic Brady DSL based on RSpec
  • 7. BDD? Better way to explain TDD
  • 10. TDD? Write a failing test Make it fail for the right reasons
  • 11. TDD? Write a failing test Make it fail for the right reasons Make it pass (just about)
  • 12. TDD? Write a failing test Make it fail for the right reasons Make it pass (just about) Refactor
  • 13. Unit Testing XP: test everything that can possibly break
  • 14. Unit Testing XP: test everything that can possibly break Unit: vague and structural 1:1
  • 15. Unit Testing XP: test everything that can possibly break Unit: vague and structural 1:1 Focus on code not behaviour
  • 16. It’s all in the mind It’s soo simple, it does not need tests
  • 17. It’s all in the mind It’s soo simple, it does not need tests I’ve done this millions of times
  • 18. It’s all in the mind It’s soo simple, it does not need tests I’ve done this millions of times I will write my code rst and test if I have time
  • 21. Test
  • 22. Test
  • 24. class CalculatorTest becomes class DescribeCalculator
  • 28. class CalculatorTest extends SomeTestFramework_TestCase becomes class DescribeCalculator extends PHPSpecContext
  • 32. testAddWithNoArguments() becomes itReturnsZeroWithNoArguments()
  • 36. $this->assertEquals(0, $result); becomes $result->should->be(0);
  • 37. Installing PEAR (soon...) # pear channel-discover pear.phpspec.net Adding Channel "pear.phpspec.net" succeeded Discovery of channel "pear.phpspec.net" succeeded # pear config-set preferred_state beta # pear install --alldeps phpspec/PHPSpec GITHUB $ git clone git://github.com/phpspec/phpspec.git
  • 38. Set initial state # StringCalculatorSpec.php <?php class DescribeStringCalculator extends PHPSpecContext { function before() { $this->calculator = $this->spec(new StringCalculator); } }
  • 39. PHPSpec DSL class DescribeStringCalculator extends PHPSpecContext { ... function itReturnsZeroWithNoArguments() { $this->calculator->add()->should->be(0); } }
  • 40. Lets run our specs $ phpspec StringCalculatorSpec.php -c .. Finished in 0.055689 seconds 2 examples, 0 failures
  • 41. Pending examples function itReturnsTheBareNumber() { $this->pending('Waiting to clarify the spec'); }
  • 42. $ phpspec StringCalculatorSpec.php -c ..* Pending: String Calculator returns the bare number # Waiting to clarify the spec # ./spec/StringCalculatorSpec.php:19 Finished in 0.056134 seconds 2 examples, 0 failures, 1 pending $
  • 43. Failing examples public function itReturnsTheSumOfSpaceSeparatedString() { $this->calculator->add('4 2')->should->be(6); } // this will fail because it’s not yet implemented
  • 44. $ phpspec StringCalculatorSpec.php -c .*.F Pending: String Calculator returns the bare number # Waiting to clarify the spec # ./spec/StringCalculatorSpec.php:19 Failures: 1) String Calculator returns the sum of space separate string expected 6, got NULL (using be()) # .spec/StringCalculatorSpec.php:28 Finished in 0.056134 seconds 4 examples, 1 failure, 1 pending $
  • 46. $ phpspec StringCalculatorSpec.php -c .*.F Pending: String Calculator returns the bare number # Waiting to clarify the spec # ./spec/StringCalculatorSpec.php:19 Failures: 1) String Calculator returns the sum of space separate string expected 42, not to be 24 (using be()) # .spec/StringCalculatorSpec.php:28 Finished in 0.056134 seconds 4 examples, 1 failure, 1 pending $
  • 47. Deliberate fail public function itReturnsTheBareNumber() { $this->fail('Just because'); }
  • 48. $ phpspec StringCalculatorSpec.php -c .*.F Pending: String Calculator returns the bare number # Waiting to clarify the spec # ./spec/StringCalculatorSpec.php:19 Failures: 1) String Calculator returns the sum of space separate string expected 42, got 0 (using be()) # .spec/StringCalculatorSpec.php:28 2) StringCalculator returns the sum of any white space separated string Failure/Error: Just because Finished in 0.056134 seconds 4 examples, 1 failure, 1 pending
  • 50. be($match) equal($match) beEqualTo($match) beAnInstanceOf($match) beEmpty() beFalse() beGreaterThan($match) beGreaterThanOrEqualTo($match)
  • 52. beInteger() beLessThan($match) beLessThanOrEqualTo($match) beNull() beString() beTrue() throwException($match)
  • 53. beInteger() beLessThan($match) beLessThanOrEqualTo($match) beNull() beString() beTrue() w throwException($match) ne
  • 54. Predicate Matcher $cell = $this->spec(new Cell); $cell->should->beAlive(); class Cell { protected $alive = true; public function isAlive() { return $this->alive; } ... }
  • 55. Predicate Matcher $newNode = $this->spec(new Node); $newNode->shouldNot->haveChildren(); class Node { protected $children = array(); public function hasChildren() { return count($this->children) > 0; } ... }
  • 56. User De ned Matcher class DescribeRapture extends PHPSpecContext { ... function itIsNotTheEndOfTheWorldAsWeKnowIt() { $today = new DateTime('2011-05-20'); $this->rapture->setDate($today) $this->rapture->shouldNot->happenToday(); } }
  • 57. $ phpspec RaptureSpec.php -c E Exceptions: 1) Rapture is not the end of the world as we know it Failure/Error: $this->rapture->shouldNot->happenToday(); PHPSpecException: unknown method call # ./RaptureSpec.php:19 # /usr/share/pear/PHPSpec/Runner/Example.php:168 Finished in 0.056134 seconds 1 examples, 1 exception $
  • 58. PHPSpecMatcherdefine('happenToday', function() { return array ( 'match' => function($rapture) { return $rapture->happensToday(); }, 'failure_message_for_should_not' => function($rapture) { return sprintf("expected %s not to mean kaput", $rapture->getDate()); } ); }); class DescribeRapture extends PHPSpecContext { ... function itIsNotTheEndOfTheWorldAsWeKnowIt() { $today = new DateTime('2011-05-20'); $this->rapture->setDate($today) $this->rapture->shouldNot->happenToday(); } }
  • 60. PHPSpecMatcherdefine('contain', function($course) { return array ( 'match' => function($repository) use ($course) { return $repository->has($course); }, 'failure_message_for_should' => function($repository) use ($course) { return "expected $course to be in repository"; } ); }); class DescribeCourseRepository extends PHPSpecContext { ... function itAddsNewCourses() { $course = new Course("BDD with PHPSpec"); $this->courses->add($course); $this->courses->should->contain(course); } }
  • 61. $ phpspec CourseRepositorySpec.php -c F Failures: 1) Course Repository adds new courses Failure/Error: $this->courses->should->contain(course); expected 'BDD with PHPSpec' to be in repository # ./CourseRepository.php:19 Finished in 0.056134 seconds 1 examples, 1 failure $
  • 62. Hooks before() after() beforeAll() afterAll()
  • 63. Mocks
  • 65. Stub Example $greeter = stub('Greeter'); $greeter->stub('greet')->andReturn('Hello Mocks!'); $hello = $this->spec(new HelloWorld($greeter)); $hello->sayHello()->should->equal('Hello Mocks!');
  • 66. Partial Stub $greeter = mock('Greeter'); $greeter ->stub('greet') ->shouldReceive('Chuck') ->andReturn('Hello Chuck!'); $hello = $this->spec(new HelloWorld($greeter)); $hello->sayHello()->should->equal('Hello Chuck!');
  • 67. Shortcut $greeter = stub('Greeter', array('greet' => 'Hello World!')); $hello = $this->spec(new HelloWorld($greeter)); $hello->sayHello()->should->equal('Hello World!');
  • 68. Mocks and hinted type class HelloWorld { public function __construct(Greeter $greeter) // <-- type { ... } } $greeter = mock('Greeter'); // <-- we are covered
  • 69. Empty doubles class HelloWorld { public function __construct($greeter) // <-- no type { ... } } $greeter = mock(); // <-- no need for types
  • 70. Counters $greeter ->stub('greet')->andReturn('Hello Chuck!') ->exactly(42); $greeter ->stub('greet')->andReturn('Hello Chuck!') ->never();
  • 71. Coming soon (more counters) $greeter ->stub('greet')->andReturn('Hello Chuck!') ->atLeast(2); $greeter ->stub('greet')->andReturn('Hello Chuck!') ->atMost(5); $greeter ->stub('greet')->andReturn('Hello Chuck!') ->between('2..5');
  • 72. Coming soon (stub chain) Instead of $frontController = double(); $dispatcher = double(); $route = double(); $request = double(); $request->stub('frontController') ->andReturn($frontController); $frontController->stub('dispatcher')->andReturn($dispatcher); $dispatcher->stub('route')->andReturn($route); $route->stub('request')->andReturn($request);
  • 73. Coming soon (stub chain) You can have $request->stubChain('frontController', 'dispatcher', 'route', 'request');
  • 74. More to come CI friendly reports functional approach backtrace fail fast autorun run single examples integration with ZF and Kohana
  • 75. Links http://github.com/phpspec/phpspec http://github/phpspec/phpspec-mocks http://www.phpspec.net http://dannorth.net/introducing-bdd http://twitter.com/_md http://twitter.com/phpspec
  • 76. Thank you! Marcello Duarte @_md http://joind.in/talk/view/3469 is hiring. Come talk to me.

Hinweis der Redaktion

  1. \n
  2. \n
  3. Differs from normal practice in terms of effort and awareness\n
  4. Differs from normal practice in terms of effort and awareness\n
  5. Differs from normal practice in terms of effort and awareness\n
  6. tester hat\n
  7. Differs from normal practice in terms of effort and awareness\n
  8. Differs from normal practice in terms of effort and awareness\n
  9. Differs from normal practice in terms of effort and awareness\n
  10. Differs from normal practice in terms of effort and awareness\n
  11. Differs from normal practice in terms of effort and awareness\n
  12. Differs from normal practice in terms of effort and awareness\n
  13. Differs from normal practice in terms of effort and awareness\n
  14. Differs from normal practice in terms of effort and awareness\n
  15. Differs from normal practice in terms of effort and awareness\n
  16. Differs from normal practice in terms of effort and awareness\n
  17. Differs from normal practice in terms of effort and awareness\n
  18. Differs from normal practice in terms of effort and awareness\n
  19. Differs from normal practice in terms of effort and awareness\n
  20. Differs from normal practice in terms of effort and awareness\n
  21. Differs from normal practice in terms of effort and awareness\n
  22. Differs from normal practice in terms of effort and awareness\n
  23. Differs from normal practice in terms of effort and awareness\n
  24. Differs from normal practice in terms of effort and awareness\n
  25. Differs from normal practice in terms of effort and awareness\n
  26. Differs from normal practice in terms of effort and awareness\n
  27. Differs from normal practice in terms of effort and awareness\n
  28. Differs from normal practice in terms of effort and awareness\n
  29. Differs from normal practice in terms of effort and awareness\n
  30. Differs from normal practice in terms of effort and awareness\n
  31. Differs from normal practice in terms of effort and awareness\n
  32. Differs from normal practice in terms of effort and awareness\n
  33. Differs from normal practice in terms of effort and awareness\n
  34. Differs from normal practice in terms of effort and awareness\n
  35. Differs from normal practice in terms of effort and awareness\n
  36. Differs from normal practice in terms of effort and awareness\n
  37. Differs from normal practice in terms of effort and awareness\n
  38. Differs from normal practice in terms of effort and awareness\n
  39. Differs from normal practice in terms of effort and awareness\n
  40. Differs from normal practice in terms of effort and awareness\n
  41. Differs from normal practice in terms of effort and awareness\n
  42. Differs from normal practice in terms of effort and awareness\n
  43. Differs from normal practice in terms of effort and awareness\n
  44. Differs from normal practice in terms of effort and awareness\n
  45. Differs from normal practice in terms of effort and awareness\n
  46. Differs from normal practice in terms of effort and awareness\n
  47. Differs from normal practice in terms of effort and awareness\n
  48. Differs from normal practice in terms of effort and awareness\n
  49. Differs from normal practice in terms of effort and awareness\n
  50. Differs from normal practice in terms of effort and awareness\n
  51. Differs from normal practice in terms of effort and awareness\n
  52. Differs from normal practice in terms of effort and awareness\n
  53. Differs from normal practice in terms of effort and awareness\n
  54. http://farm5.static.flickr.com/4140/4926597784_4392361eb6_b_d.jpg\n
  55. Differs from normal practice in terms of effort and awareness\n
  56. Differs from normal practice in terms of effort and awareness\n
  57. Differs from normal practice in terms of effort and awareness\n
  58. Differs from normal practice in terms of effort and awareness\n
  59. Differs from normal practice in terms of effort and awareness\n
  60. Differs from normal practice in terms of effort and awareness\n
  61. Differs from normal practice in terms of effort and awareness\n
  62. Differs from normal practice in terms of effort and awareness\n
  63. Differs from normal practice in terms of effort and awareness\n
  64. Differs from normal practice in terms of effort and awareness\n
  65. Differs from normal practice in terms of effort and awareness\n
  66. Differs from normal practice in terms of effort and awareness\n
  67. Differs from normal practice in terms of effort and awareness\n
  68. Differs from normal practice in terms of effort and awareness\n
  69. Differs from normal practice in terms of effort and awareness\n
  70. Differs from normal practice in terms of effort and awareness\n
  71. Differs from normal practice in terms of effort and awareness\n