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
|
|
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
- Based on a gist from Pedro Borges
- Inspired by Marcello Duarte's PhpSpec 2.0 ilustrated by examples slides
- Converted by Jens Kohl