mercredi 7 janvier 2015

Laravel unit testing how to mock eloquent's query scope method

I would like to mock model's scope method, is it possible? How?


Here is the scenario:


Order model:



public function scopeForUser($query) // query scope method which should be mocked
{

return $query->where('user_id', 1);
}


User model:



public function getOrders()
{

$orders = $this->orders(); // Returns Eloquent object(HasMany)

$orders->forUser(); // I would like to mock forUser() method

return $orders->get();
}


TestCase:



public function testGetUsersOrders()
{
$userOrders = Order::where('user_id', 1);

// Mock Order's forUser method
$this->mock = Mockery::mock('Eloquent', 'Order'); // ?? I can't mock HasMany object, can I?
$this->app->instance('Order', $this->mock);

$this->mock->shouldReceive('forUser')->once()->andReturn($userOrders->get());

$result = $this->user->getOrders();
$this->assertEquals($userOrders->get(), $result);

}


This is simplified example.


Aucun commentaire:

Enregistrer un commentaire