Skip to main content

Tests actingAs(): No Need to Send Tokens

Premium
2 min read

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 of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.