Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Incremental APIs: Level 9 - Tests (Readable Ones!)
<?php
use Faker\Factory as Faker;
class ApiTester extends TestCase {
/**
* @var Faker
*/
protected $fake;
/**
* @var int
*/
protected $times = 1;
/**
* Initialize
*/
function __construct()
{
$this->fake = Faker::create();
}
/**
* Setup database for each test
*/
public function setUp()
{
parent::setUp();
$this->app['artisan']->call('migrate');
}
/**
* Number of times to make entities
*
* @param $count
* @return $this
*/
protected function times($count)
{
$this->times = $count;
return $this;
}
/**
* Get JSON output from API
*
* @param $uri
* @return mixed
*/
protected function getJson($uri)
{
return json_decode($this->call('GET', $uri)->getContent());
}
/**
* Assert object has any number of attributes
*
*/
protected function assertObjectHasAttributes()
{
$args = func_get_args();
$object = array_shift($args);
foreach ($args as $attribute)
{
$this->assertObjectHasAttribute($attribute, $object);
}
}
}
<?php
class LessonsTest extends ApiTester {
/** @test */
public function it_fetches_lessons()
{
$this->makeLesson();
$this->getJson('api/v1/lessons');
$this->assertResponseOk();
}
/** @test */
public function it_fetches_a_single_lesson()
{
$this->makeLesson();
$lesson = $this->getJson('api/v1/lessons/1')->data;
$this->assertResponseOk();
$this->assertObjectHasAttributes($lesson, 'body', 'active');
}
/** @test */
public function it_404s_if_a_lesson_is_not_found()
{
$this->getJson('api/v1/lessons/x');
$this->assertResponseStatus(404);
}
private function makeLesson($lessonFields = [])
{
$lesson = array_merge([
'title' => $this->fake->sentence,
'body' => $this->fake->paragraph,
'some_bool' => $this->fake->boolean
], $lessonFields);
while($this->times--) Lesson::create($lesson);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.