Link to the repository
[Only for premium members]
[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...