Skip to content

Instantly share code, notes, and snippets.

@archy-bold
Last active October 15, 2022 03:49
Show Gist options
  • Save archy-bold/bd696e8ec84a7657b724523e07fd7a6c to your computer and use it in GitHub Desktop.
Save archy-bold/bd696e8ec84a7657b724523e07fd7a6c to your computer and use it in GitHub Desktop.
Testing Passport Authenticated Controllers and Routes in Laravel
{
...
"autoload-dev": {
"classmap": [
"tests/TestCase.php",
"tests/PassportTestCase.php"
]
},
...
}
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExamplePassportTest extends \PassportTestCase
{
use DatabaseTransactions;
protected $scopes = ['restricted-scope'];
public function testRestrictedRoute()
{
$this->get('/api/user')
->assertResponseStatus(401);
}
public function testUnrestrictedRoute()
{
$this->get('/api/restricted')
->assertResponseOk();
}
}
<?php
use App\User;
use Laravel\Passport\ClientRepository;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PassportTestCase extends TestCase
{
use DatabaseTransactions;
protected $headers = [];
protected $scopes = [];
protected $user;
public function setUp()
{
parent::setUp();
$clientRepository = new ClientRepository();
$client = $clientRepository->createPersonalAccessClient(
null, 'Test Personal Access Client', $this->baseUrl
);
DB::table('oauth_personal_access_clients')->insert([
'client_id' => $client->id,
'created_at' => new DateTime,
'updated_at' => new DateTime,
]);
$this->user = factory(User::class)->create();
$token = $this->user->createToken('TestToken', $this->scopes)->accessToken;
$this->headers['Accept'] = 'application/json';
$this->headers['Authorization'] = 'Bearer '.$token;
}
public function get($uri, array $headers = [])
{
return parent::get($uri, array_merge($this->headers, $headers));
}
public function getJson($uri, array $headers = [])
{
return parent::getJson($uri, array_merge($this->headers, $headers));
}
public function post($uri, array $data = [], array $headers = [])
{
return parent::post($uri, $data, array_merge($this->headers, $headers));
}
public function postJson($uri, array $data = [], array $headers = [])
{
return parent::postJson($uri, $data, array_merge($this->headers, $headers));
}
public function put($uri, array $data = [], array $headers = [])
{
return parent::put($uri, $data, array_merge($this->headers, $headers));
}
public function putJson($uri, array $data = [], array $headers = [])
{
return parent::putJson($uri, $data, array_merge($this->headers, $headers));
}
public function patch($uri, array $data = [], array $headers = [])
{
return parent::patch($uri, $data, array_merge($this->headers, $headers));
}
public function patchJson($uri, array $data = [], array $headers = [])
{
return parent::patchJson($uri, $data, array_merge($this->headers, $headers));
}
public function delete($uri, array $data = [], array $headers = [])
{
return parent::delete($uri, $data, array_merge($this->headers, $headers));
}
public function deleteJson($uri, array $data = [], array $headers = [])
{
return parent::deleteJson($uri, $data, array_merge($this->headers, $headers));
}
}
@datashaman
Copy link

With Laravel 5.4+ you can use this very simple method to test passport routes: https://laravel.com/docs/5.7/passport#testing

@hfatahi
Copy link

hfatahi commented Feb 27, 2019

@archy-bold Is this any different than simply calling Passport::actingAs()?

@hemantachhami19
Copy link

searching for this .you saved my life sir . thank you 👍

@archy-bold
Copy link
Author

Thanks @hemantachhami19, as has been said; you can just use Passport::actingAs($user) now instead of all this scaffolding.

Same for this @hfatahi @hindermyertim @AhmedHelalAhmed (only just got notifications)

@Maxcrazy1
Copy link

Crack of cracks 👑

@cAstraea
Copy link

@archy-bold do you have an example please ? I could never get actingAs to work in my tests... keep getting all sorts of weird errors like
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::withAccessToken does not exist.

@archy-bold
Copy link
Author

Hi @cAstraea. There's really not much to it, there's an example in the Passport documentation. If you're still experiencing errors, I imagine it's one of two things:

  1. You've not installed Passport correctly or not run the migrations on your test database. The documentation on installing should help you get it all set up. It will be worth checking the traits are on your model too.
  2. You might not be passing a single User model to the actingAs() function. Maybe it's worth dd()ing what you're passing to the function. It might be a QueryBuilder, or Collection object rather than a User model.

Hope that helps.

@cAstraea
Copy link

Thanks yea that was it thank you 🤣 Dunno what I was thinking calling it on collection

@archy-bold
Copy link
Author

@cAstraea I usually blame tiredness!

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