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 act on the user's behalf without sending the token manually each time with the $this->actingAs()
method.
This is the "Laravel way" version:
tests/Feature/OrderCreateTest.php:
class OrderCreateTest extends TestCase{ use RefreshDatabase; public function test_create_order_successfully() { [$token, $user] = $this->createAuthUserToken(); $response = $this->withHeaders([ 'Authorization' => 'Bearer '.$token, ])->postJson('/api/v1/orders', $orderData); $user = User::factory()->create(); $response = $this ->actingAs($user) ->postJson('/api/v1/orders', $orderData);
Then, we make similar changes in all other places where the Bearer token is used.
And then, as you see above, we can totally remove the method createAuthUserToken()
from the TestCase class. We don't really need that token. Let Laravel auto-handle it under the hood.
Here's the full GitHub commit for this change and minor fix afterward.
No comments yet…