Skip to content

Instantly share code, notes, and snippets.

@jwalton512
Created August 9, 2015 08:46
Show Gist options
  • Save jwalton512/e3b320bef85be88e8bd5 to your computer and use it in GitHub Desktop.
Save jwalton512/e3b320bef85be88e8bd5 to your computer and use it in GitHub Desktop.
Api Testing With Laravel 5.1 (jwt-auth)
<?php
namespace Tests\Api;
use App\User;
use Tests\TestCase as BaseTestCase;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class TestCase extends BaseTestCase
{
/**
* @var User
*/
protected $user;
/**
* Set the currently logged in user for the application.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string|null $driver
* @return $this
*/
public function actingAs(UserContract $user, $driver = null)
{
$this->user = $user;
return $this;
}
/**
* Call the given URI and return the Response.
*
* @param string $method
* @param string $uri
* @param array $parameters
* @param array $cookies
* @param array $files
* @param array $server
* @param string $content
* @return \Illuminate\Http\Response
*/
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
if ($this->user) {
$server['HTTP_AUTHORIZATION'] = 'Bearer ' . \JWTAuth::fromUser($this->user);
}
$server['HTTP_ACCEPT'] = 'application/json';
return parent::call($method, $uri, $parameters, $cookies, $files, $server, $content);
}
/**
* @return $this
*/
protected function actingAsAdmin()
{
return $this->actingAs(factory(User::class, 'admin')->create());
}
}
<?php
namespace Tests\Api\Admin;
use App\Track;
use Tests\Api\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class TrackTest extends TestCase
{
use DatabaseMigrations;
/** @test */
public function it_should_list_tracks()
{
factory(Track::class, 3)->create();
$this->actingAsAdmin()
->get("api/admin/tracks")
->seeStatusCode(200)
->assertCount(3, json_decode($this->response->getContent()));
}
/** @test */
public function it_should_create_tracks()
{
$data = ['name' => 'FooBar'];
$this->actingAsAdmin()
->post('api/admin/tracks', $data)
->seeStatusCode(200)
->seeInDatabase('tracks', ['name' => 'FooBar']);
}
/** @test */
public function it_should_update_tracks()
{
$track = factory(Track::class)->create(['name' => 'FooBar']);
$data = ['name' => 'FooBarBaz'];
$this->actingAsAdmin()
->post("api/admin/tracks/{$track->id}", $data)
->seeStatusCode(200)
->seeInDatabase('tracks', ['name' => 'FooBarBaz']);
}
/** @test */
public function it_should_delete_tracks()
{
$track = factory(Track::class)->create(['name' => 'FooBar']);
$this->actingAsAdmin()
->delete("api/admin/tracks/{$track->id}")
->seeStatusCode(204)
->notSeeInDatabase('tracks', ['id' => $track->id]);
}
}
@acro5piano
Copy link

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment