From Marcello Duarte's PhpSpec 2.0 ilustrated by examples slides (http://pt.slideshare.net/marcello.duarte/phpspec-20-ilustrated-by-examples) #php #phpspec #cheatsheet
Object: $result
($this
)
Expectation: should
or shouldNot
Matcher: Be...()
Types of Matchers:
Identity (===)
<?php
$this->method()->shouldReturn('something');
$this->method()->shouldBe('something');
$this->method()->shouldBeEqualTo('something');
$this->method()->shouldEqual('something');
Comparison (==)
<?php
$this->method()->shouldBeLike('something');
Throw
<?php
$this->shouldThrow('EndOfTheWorld')->duringGreet();
$this->shouldThrow('EndOfTheWorld')->during('greet');
$this->greet()->shouldThrow(new \Exception)->duringGreet();
$this->greet()->shouldThrow(new \Exception)->during('greet', ['arguments']);
Type
<?php
$this->greet()->shouldBeAnInstanceOf('Greeting');
$this->greet()->returnAnInstanceOf('Greeting');
$this->greet()->haveType('Greeting');
Object State
<?php
class ShoppingCartSpec extends ObjectBehavior
{
function it_is_created_empty()
{
$this->shouldNotHaveItems();
}
}
class ShoppingCart
{
public function hasItem() {}
}
<?php
class LifeSpec extends ObjectBehavior
{
function it_is_simple()
{
$this->shouldBeSimple();
}
}
class Life
{
public function isSimple() {}
}
Inline
<?php
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:
<?php
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:
<?php
//...
function let()
{
$this->beConstructedWith('Hello, World!');
}
Stubbing:
<?php
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:
<?php
class SomeSpec extends ObjectBehavior
{
function let(Greeter $greeter)
{
$this->beConstructedWith($greeter);
}
function it_uses_a_greeter(Greeter $greeter)
{
$greeting->sayHelloWorld()->shouldBeCalled();
$this->greet();
}
}
Added <?php
in some samples solely for syntax highligthing.