nedf23
5/21/2013 - 10:37 PM

Testing APIs in Laravel. Thoughts?

Testing APIs in Laravel. Thoughts?

<?php


class PhotoApiTest extends TestCase {
    
    public function setUp()
    {
        parent::setUp();

        Route::enableFilters();

        Artisan::call('migrate');
        Artisan::call('db:seed');

        Auth::loginUsingId(1);

        // OR:
        //$this->be(User::find(1));
    }

    public function testMustBeAuthenticated()
    {
        Auth::logout();
        $response = $this->call('GET', 'api/v1/photos');

        $this->assertEquals('Invalid credentials.', $response->getContent());
    }

    public function testProvidesErrorFeedback()
    {
        $response = $this->call('GET', 'api/v1/photos');
        $data = $this->parseJson($response);

        $this->assertEquals(false, $data->error);
    }

    public function testFetchesAllPhotosForUser()
    {
        $response = $this->call('GET', 'api/v1/photos');
        $data = $this->parseJson($response);

        $this->assertIsJson($data);
        $this->assertInternalType('array', $data->photos);
    }

    public function testCreatesPhoto()
    {
        $photo = [
            'caption' => 'My new photo',
            'path'    => 'foo.jpg',
            'user_id' => 1
        ];
        $response = $this->call('POST', 'api/v1/photos', $photo);
        $data = $this->parseJson($response);

        $this->assertEquals(false, $data->error);
        $this->assertEquals('Photo was created', $data->message);
    }

    protected function parseJson(Illuminate\Http\JsonResponse $response)
    {
        return json_decode($response->getContent());
    }

    protected function assertIsJson($data)
    {
        $this->assertEquals(0, json_last_error());
    }

}