Created
April 9, 2014 23:53
-
-
Save laracasts/10331246 to your computer and use it in GitHub Desktop.
Incremental APIs: Level 9 - Tests (Readable Ones!)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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