phpSpec

Enjoy this cheat sheet at its fullest within Dash, the macOS documentation browser.

General

Object

$result ($this)

Expectation

should or shouldNot

Matcher

Be...()

Types of Matchers

Identity (===)

$this->method()->shouldReturn('something');
$this->method()->shouldBe('something');
$this->method()->shouldBeEqualTo('something');
$this->method()->shouldEqual('something');

Comparison (==)

$this->method()->shouldBeLike('something');

Throw

$this->shouldThrow('EndOfTheWorld')->duringGreet();
$this->shouldThrow('EndOfTheWorld')->during('greet');
$this->greet()->shouldThrow(new \Exception)->duringGreet();
$this->greet()->shouldThrow(new \Exception)->during('greet', ['arguments']);

Type

$this->greet()->shouldBeAnInstanceOf('Greeting');
$this->greet()->returnAnInstanceOf('Greeting');
$this->greet()->haveType('Greeting');

Object State

  • has → have

    class ShoppingCartSpec extends ObjectBehavior
    {
      function it_is_created_empty()
      {
        $this->shouldNotHaveItems();
      }
    }
    
    class ShoppingCart
    {
      public function hasItem() {}
    }
  • is → be

    class LifeSpec extends ObjectBehavior
    {
      function it_is_simple()
      {
        $this->shouldBeSimple();
      }
    }
    
    class Life
    {
      public function isSimple() {}
    }

Inline

class NeoSpec extends ObjectBehavior
{
  function it_should_be_the_one()
  {
    $this->shouldBeTheOne();
  }
  function getMatchers()
  {
    return [
      'beTheOne' => function($actual)
      {
        return $actual instanceOf TheOne;
      }
    ];
  }
}

Let & Let Go

class SomeSpec extends ObjectBehavior
{
    function let()
    {
      // run before every example
    }

    function it_greets_with_hello()
    {
      $this->greet()->shouldReturn('Hello, World!');
    }

    function let_go()
    {
      // run after every example
    }
}

Constructors

//...

function let()
{
  $this->beConstructedWith('Hello, World!');
}

Stubbing

class SomeSpec extends ObjectBehavior
{
    function let(Greeting $greeting)
    {
      $this->beConstructedWith($greeting); 
    }

    function it_greets_with_hello_world(Greeting $greeting)
    {
      $greeting->getMessage()->willReturn('Hello, World!');

      $this->greet()->shouldReturn('Hello, World!');
    }
}

Mocking

class SomeSpec extends ObjectBehavior
{
    function let(Greeter $greeter)
    {
      $this->beConstructedWith($greeter); 
    }

    function it_uses_a_greeter(Greeter $greeter)
    {
      $greeting->sayHelloWorld()->shouldBeCalled();

      $this->greet();
    }
}

Notes