Skip to content

Instantly share code, notes, and snippets.

@jgardezi
Forked from JeffreyWay/BaseModel.php
Created August 31, 2017 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgardezi/b579f110a61868ee50da0867d1c5fa87 to your computer and use it in GitHub Desktop.
Save jgardezi/b579f110a61868ee50da0867d1c5fa87 to your computer and use it in GitHub Desktop.
To make for clean and readable tests, do your mocking in a base model that your Eloquent models extend.
<?php
class BaseModel extends Eloquent {
public static function shouldReceive()
{
$repo = get_called_class() . 'RepositoryInterface';
$mock = Mockery::mock($repo);
App::instance($repo, $mock);
return call_user_func_array(array($mock, 'shouldReceive'), func_get_args());
}
}
<?php
class PostsTest extends TestCase {
public function testAllPosts()
{
// This will mock the PostRepository interface, update the instance
// that will be injected into the controller (use DI), and stub the getAll method.
// This way, the DB will never be hit.
Post::shouldReceive('getAll')->andReturn('foo');
// Call the route.
$response = $this->call('GET', 'posts');
// Make sure that the request was successful.
$this->assertTrue($response->isOk());
// also make sure that $posts is bound to the view
$this->assertEquals('foo', $response->getOriginalContent()->posts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment