Reputation: 2819
i'm testing laravel controller. Here's the respective route
Route::get('categories', array('as'=>'categories', 'uses'=>'CategoryController@getCategory'));
Here's the controller:
<?php
// app/controllers/CategoryController.php
class CategoryController extends BaseController {
//Loading Category model instance in constructor
public function __construct(Category $category){
$this->category = $category;
}
public function getCategory(){
$categories = $this->category->all();
return View::make('dashboard.showcategories')->with('categories', $categories);
}
}
In the view dashboard.showcategories
, i have used foreach to loop through the $categories
variable and have then used it.
Now i was trying to test this controller.
<?php
// app/tests/controllers/CategoryControllerTest
class CategoryControllerTest extends TestCase {
public function __construct(){
$this->mock = Mockery::mock('Eloquent', 'Category');
}
public function tearDown(){
Mockery::close();
}
public function testGetCategory(){
$this->mock
->shouldReceive('all')
->once();
$this->app->instance('Category', $this->mock);
$response = $this->call('GET', 'categories');
$categories = $response->original->getData()['categories'];
$this->assertViewHas('categories');
$this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $categories);
}
}
But it's showing an error
There was 1 error:
1) CategoryControllerTest::testGetCategory
ErrorException: Invalid argument supplied for foreach() (View: /var/www/Hututoo/app/views/dashboard/showcategories.blade.php)
However, if i delete following code from the test, it passes.
$this->mock
->shouldReceive('all')
->once();
$this->app->instance('Category', $this->mock);
How to make this test pass with mockery?
In case you need Category model
<?php
// app/models/Category.php
use Jenssegers\Mongodb\Model as Eloquent;
class Category extends Eloquent {
protected $table = 'category';
protected $fillable = array('category_name', 'options');
}
Upvotes: 0
Views: 456
Reputation: 4059
your mock does not return anything, and your foreach loop is expecting an array to loop over.
try setting a return value of an empty array
$this->mock
->shouldReceive('all')
->once()
->andReturn(new Illuminate\Database\Eloquent\Collection);
Upvotes: 2