Created
September 15, 2025 00:41
-
-
Save shahmal1yev/d1b23c40ef3e8af7f1a454b38271e1ac to your computer and use it in GitHub Desktop.
Laravel API Testing Traits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| trait WithAuth | |
| { | |
| use WithUser; | |
| public function getJson($uri, array $headers = [], $options = 0) | |
| { | |
| $this->actingAs(); | |
| return parent::getJson($uri, $headers, $options); | |
| } | |
| public function postJson($uri, array $data = [], array $headers = [], $options = 0) | |
| { | |
| $this->actingAs(); | |
| return parent::postJson($uri, $data, $headers, $options); | |
| } | |
| public function putJson($uri, array $data = [], array $headers = [], $options = 0) | |
| { | |
| $this->actingAs(); | |
| return parent::putJson($uri, $data, $headers, $options); | |
| } | |
| public function patchJson($uri, array $data = [], array $headers = [], $options = 0) | |
| { | |
| $this->actingAs(); | |
| return parent::patchJson($uri, $data, $headers, $options); | |
| } | |
| public function deleteJson($uri, array $data = [], array $headers = [], $options = 0) | |
| { | |
| $this->actingAs(); | |
| return parent::deleteJson($uri, $data, $headers, $options); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| trait WithUser | |
| { | |
| protected ?User $user = null; | |
| protected Role|RoleModel|null $role = Role::ADMIN; | |
| protected function resolveUser(): ?User | |
| { | |
| if ($this->role === null) { | |
| return null; | |
| } | |
| if ($this->user === null) { | |
| if ($this->role instanceof Role) { | |
| $this->role = RoleModel::query()->firstOrCreate([ | |
| 'name' => $this->role, | |
| 'guard_name' => 'api', | |
| ]); | |
| } | |
| $this->user = User::factory()->create()->assignRole($this->role); | |
| } | |
| return $this->user; | |
| } | |
| public function actingAs(?UserContract $user = null, $guard = null): static | |
| { | |
| if ($resolvedUser = $this->resolveUser()) { | |
| return parent::actingAs($user ?? $resolvedUser, $guard ?? 'api'); | |
| } | |
| return $this; | |
| } | |
| protected function withRole(?Role $role): self | |
| { | |
| $this->role = $role; | |
| $this->user = null; | |
| return $this; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment