Courses

Laravel API Code Review and Refactor

Tests actingAs(): No Need to Send Tokens

You're reading a FREE PREVIEW of a PREMIUM course.

Link to the repository

[Only for premium members]

When looking at the tests, I noticed the repeating code to create a new user and then perform the API call using Bearer Token.

tests/Feature/OrderCreateTest.php:

class OrderCreateTest extends TestCase
{
use RefreshDatabase;
 
public function test_create_order_successfully()
{
[$token, $user] = $this->createAuthUserToken();
 
// ...
 
// Send a POST request to create the order with the token in the headers
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token,
])->postJson('/api/v1/orders', $orderData);
 
// ...

That createAuthUserToken() is defined in the base TestCase, like this:

tests/TestCase.php:

abstract class TestCase extends BaseTestCase
{
protected function createAuthUserToken(): array
{
// Create a user
$user = \App\Models\User::factory()->create();
 
// Generate a Sanctum token for the user
return [$user->createToken('auth_token')->plainTextToken, $user];
}
}

This is another example of how the code works but is not written in a "native Laravel" way. Laravel allows you to...

The full lesson is only for Premium Members.
Want to access all 15 lessons of this course? (56 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord