Skip to content

Instantly share code, notes, and snippets.

@aaroneaton
Last active September 16, 2016 02:58
Show Gist options
  • Save aaroneaton/9701eef8c3b18d3f9c9bd9191f47f012 to your computer and use it in GitHub Desktop.
Save aaroneaton/9701eef8c3b18d3f9c9bd9191f47f012 to your computer and use it in GitHub Desktop.
Using WP_Mock with PhpSpec
<?php
class TodoSpec extends ObjectBehavior {
public function let() {
\WP_Mock::setUp();
}
public function letGo() {
\WP_Mock::tearDown();
}
}
<?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);
}
}
<?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