Ok, solved it finally.
PeopleController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\Activity;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Contracts\PersonRepositoryInterface;
class PeopleController extends Controller
{
protected $person;
protected $activity;
public function __construct(PersonRepositoryInterface $person, Activity $activity)
{
$this->person = $person;
$this->activity = $activity;
}
public function index()
{
$people = $this->person->getPaginated();
return view('people.index', ['people' => $people]);
}
}
PersonRepositoryInterface.php
<?php
namespace App\Contracts;
interface PersonRepositoryInterface
{
public function getPaginated($paginate = 20);
}
PersonRepository.php
<?php
namespace App\Repos;
use Auth;
use App\Person;
use App\Abstracts\DbRepository;
use App\Contracts\PersonRepositoryInterface;
class PersonRepository extends DbRepository implements PersonRepositoryInterface
{
protected $model;
public function __construct(Person $model)
{
$this->model = $model;
}
public function getPaginated($pageSize = 20)
{
return $this->model->where([
'team_id' => Auth::user()->currentTeam()->id
])->paginate($pageSize);
}
}
PeopleControllerTest.php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PeopleControllerTest extends TestCase
{
use WithoutMiddleware;
public function tearDown()
{
Mockery::close();
}
public function setUp()
{
parent::setUp();
$this->mock('App\Contracts\PersonRepositoryInterface');
}
public function mock($class)
{
$this->mock = Mockery::mock($class);
$this->app->instance($class, $this->mock);
return $this->mock;
}
public function testIndex()
{
$this->mock->shouldReceive('getPaginated')->once();
$response = $this->call('GET', 'people');
$this->assertResponseOk();
}
}
There were a couple things that enlightened me...
I don't need to care what is returned back at this point (maybe I will later, but not for now). So, assertResponseOk() and shouldReceive('getPaginated')->once(); should be just fine for the moment.
I needed to mock the interface, not the model, since that's what I'm injecting. Duh. I should have seen that one.
As many have said before, it's ok to not inject Auth into a custom repository function (for now). I may want to do that later when I write tests for the repository itself, though. But for the purposes of this issue/exercise, it wasn't necessary.
You may notice I created an extra little helper function to make future tests in this PeopleControllerTest.php faster/easier, since there's a pattern there. Thanks to Jeffrey Way's old tuts+ post for that one.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community