I'm trying to properly mock a chained call to an Eloquent model in a controller. In my controller I'm using dependancy injection to access the model so that it should be easy to mock, however I'm not sure how to test the chained calls and make it work right. This is all in Laravel 4.1 using PHPUnit and Mockery.
Controller:
<?php
class TextbooksController extends BaseController
{
protected $textbook;
public function __construct(Textbook $textbook)
{
$this->textbook = $textbook;
}
public function index()
{
$textbooks = $this->textbook->remember(5)
->with('user')
->notSold()
->take(25)
->orderBy('created_at', 'desc')
->get();
return View::make('textbooks.index', compact('textbooks'));
}
}
Controller test:
<?php
class TextbooksControllerText extends TestCase
{
public function __construct()
{
$this->mock = Mockery::mock('Eloquent', 'Textbook');
}
public function tearDown()
{
Mockery::close();
}
public function testIndex()
{
// Here I want properly mock my chained call to the Textbook
// model.
$this->action('GET', 'TextbooksController@index');
$this->assertResponseOk();
$this->assertViewHas('textbooks');
}
}
I've been trying to achieve this by placing this code before the $this->action()
call in the test.
$this->mock->shouldReceive('remember')->with(5)->once();
$this->mock->shouldReceive('with')->with('user')->once();
$this->mock->shouldReceive('notSold')->once();
$this->app->instance('Textbook', $this->mock);
However, this results in the error Fatal error: Call to a member function with() on a non-object in /app/controllers/TextbooksController.php on line 28
.
I've also tried a chained alternative hoping it would do the trick.
$this->mock->shouldReceive('remember')->with(5)->once()
->shouldReceive('with')->with('user')->once()
->shouldReceive('notSold')->once();
$this->app->instance('Textbook', $this->mock);
What is the best approach I should take to testing this chained method call with Mockery.