Last active
September 16, 2016 02:58
-
-
Save aaroneaton/9701eef8c3b18d3f9c9bd9191f47f012 to your computer and use it in GitHub Desktop.
Using WP_Mock with PhpSpec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class TodoSpec extends ObjectBehavior { | |
public function let() { | |
\WP_Mock::setUp(); | |
} | |
public function letGo() { | |
\WP_Mock::tearDown(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* A test written with PHPUnit | |
*/ | |
class TodoTest extends TestCase { | |
public function testCanCompleteTodo() { | |
$todo = new Todo('Write a blog post'); | |
$todo->markCompleted(); | |
$this->assertTrue($todo->isComplete()); | |
} | |
} | |
/** | |
* The same test in PhpSpec | |
*/ | |
class TodoSpec extends ObjectBehavior { | |
public function let() { | |
$this->beConstructedWith('Write a blog post'); | |
} | |
public function it_can_complete_todo() { | |
$this->markCompleted(); | |
$this->isComplete()->shouldReturn(true); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Todo { | |
private $title; | |
public function __construct( $title ) { | |
$this->title = $title; | |
} | |
public function save() { | |
return wp_insert_post(['post_title' => $this->title, 'post_status' => 'publish'], true); | |
} | |
} | |
class TodoSpec extends ObjectBehavior { | |
public function let() { | |
\WP_Mock::setUp(); | |
} | |
public function letGo() { | |
\WP_Mock::tearDown(); | |
} | |
public function it_can_create_todo() { | |
/** | |
* We are expecting that the `save()` method will call `wp_insert_post()`. | |
* If `wp_insert_post()` wasn't actually called an error would be thrown | |
* during the test. | |
*/ | |
\WP_Mock::wpFunction( 'wp_insert_post', array( | |
'args' => [['post_title' => 'Write a blog post', 'post_status' => 'publish'], true], | |
'times' => 1, | |
'return' => 42 | |
) ); | |
// Now run Todo::save() and make sure it returns the post (todo) ID | |
$this->save()->shouldReturn(42); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment