[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F0BT77CMGAE5VR7HB6KFAT":3,"skill-same:01M7F0BT77CMGAE5VR7HB6KFAT":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M7F0BT77CMGAE5VR7HB6KFAT","laravel-tdd",null,"Laravel testing strategies with PHPUnit, Pest, model factories, HTTP tests, Sanctum authentication testing, mocking, and coverage. Use when writing Laravel tests with PHPUnit or Pest, or driving a Laravel feature test-first.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fecc\u002Flaravel-tdd\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: laravel-tdd\ndescription: Laravel testing strategies with PHPUnit, Pest, model factories, HTTP tests, Sanctum authentication testing, mocking, and coverage. Use when writing Laravel tests with PHPUnit or Pest, or driving a Laravel feature test-first.\nmetadata:\n  origin: ECC\n---\n\n# Laravel Testing with TDD\n\nTest-driven development for Laravel applications using PHPUnit, Pest, Laravel factories, and testing helpers.\n\n## When to Activate\n\n- Writing new Laravel applications or features\n- Implementing API endpoints with Sanctum or Passport authentication\n- Testing Eloquent models, relationships, scopes, and accessors\n- Setting up testing infrastructure for Laravel projects\n- Writing feature tests for HTTP controllers and form requests\n- Mocking external services (queues, mail, notifications, HTTP)\n\n## TDD Workflow for Laravel\n\n### Red-Green-Refactor Cycle\n\n```php\n\u002F\u002F Step 1: RED — Write a failing test\npublic function test_a_product_can_be_created(): void\n{\n    $product = Product::factory()->create(['name' => 'Test Product']);\n    $this->assertDatabaseHas('products', ['name' => 'Test Product']);\n}\n\n\u002F\u002F Step 2: GREEN — Write the migration, model, and factory\n\u002F\u002F Step 3: REFACTOR — Improve while keeping tests green\n```\n\n## Setup\n\n### PHPUnit Configuration\n\n```xml\n\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003Cphpunit xmlns:xsi=\"http:\u002F\u002Fwww.w3.org\u002F2001\u002FXMLSchema-instance\"\n         xsi:noNamespaceSchemaLocation=\"vendor\u002Fphpunit\u002Fphpunit\u002Fphpunit.xsd\"\n         bootstrap=\"vendor\u002Fautoload.php\"\n         colors=\"true\">\n    \u003Ctestsuites>\n        \u003Ctestsuite name=\"Unit\">\n            \u003Cdirectory suffix=\"Test.php\">tests\u002FUnit\u003C\u002Fdirectory>\n        \u003C\u002Ftestsuite>\n        \u003Ctestsuite name=\"Feature\">\n            \u003Cdirectory suffix=\"Test.php\">tests\u002FFeature\u003C\u002Fdirectory>\n        \u003C\u002Ftestsuite>\n    \u003C\u002Ftestsuites>\n    \u003Cphp>\n        \u003Cenv name=\"APP_ENV\" value=\"testing\"\u002F>\n        \u003Cenv name=\"BCRYPT_ROUNDS\" value=\"4\"\u002F>\n        \u003Cenv name=\"CACHE_STORE\" value=\"array\"\u002F>\n        \u003Cenv name=\"DB_CONNECTION\" value=\"sqlite\"\u002F>\n        \u003Cenv name=\"DB_DATABASE\" value=\":memory:\"\u002F>\n        \u003Cenv name=\"MAIL_MAILER\" value=\"array\"\u002F>\n        \u003Cenv name=\"QUEUE_CONNECTION\" value=\"sync\"\u002F>\n        \u003Cenv name=\"SESSION_DRIVER\" value=\"array\"\u002F>\n    \u003C\u002Fphp>\n\u003C\u002Fphpunit>\n```\n\n### Base TestCase Setup\n\n```php\nnamespace Tests;\n\nuse Illuminate\\Foundation\\Testing\\TestCase as BaseTestCase;\n\nabstract class TestCase extends BaseTestCase\n{\n    protected function setUp(): void\n    {\n        parent::setUp();\n        \u002F\u002F Call $this->withoutExceptionHandling() only in tests that\n        \u002F\u002F test non-HTTP exceptions; it suppresses assertStatus() etc.\n    }\n\n    \u002F\u002F Helper: Authenticate and return user\n    protected function actingAsUser(): mixed\n    {\n        $user = \\App\\Models\\User::factory()->create();\n        $this->actingAs($user);\n        return $user;\n    }\n\n    protected function actingAsAdmin(): mixed\n    {\n        $admin = \\App\\Models\\User::factory()->admin()->create();\n        $this->actingAs($admin);\n        return $admin;\n    }\n}\n```\n\n## Model Factories\n\n```php\n\u002F\u002F database\u002Ffactories\u002FUserFactory.php\nclass UserFactory extends Factory\n{\n    protected static ?string $password = null;\n\n    public function definition(): array\n    {\n        return [\n            'name' => fake()->name(),\n            'email' => fake()->unique()->safeEmail(),\n            'email_verified_at' => now(),\n            'password' => static::$password ??= Hash::make('password'),\n            'remember_token' => Str::random(10),\n            'role' => 'user',\n        ];\n    }\n\n    public function admin(): static\n    {\n        return $this->state(fn (array $attributes) => ['role' => 'admin']);\n    }\n\n    public function unverified(): static\n    {\n        return $this->state(fn (array $attributes) => ['email_verified_at' => null]);\n    }\n}\n\n\u002F\u002F database\u002Ffactories\u002FProductFactory.php\nclass ProductFactory extends Factory\n{\n    public function definition(): array\n    {\n        return [\n            'name' => fake()->unique()->words(3, true),\n            'slug' => fn (array $attrs) => Str::slug($attrs['name']),\n            'description' => fake()->paragraph(),\n            'price' => fake()->numberBetween(100, 100000),\n            'stock' => fake()->numberBetween(0, 100),\n            'is_active' => true,\n            'user_id' => UserFactory::new(),\n        ];\n    }\n\n    public function outOfStock(): static\n    {\n        return $this->state(fn (array $attributes) => ['stock' => 0]);\n    }\n}\n```\n\n### Using Factories\n\n```php\n$user = User::factory()->create();\n$admin = User::factory()->admin()->create();\n$product = Product::factory()->create(['user_id' => $user->id]);\n$products = Product::factory()->count(10)->create();\n$draft = Product::factory()->make(); \u002F\u002F Not persisted\n\n\u002F\u002F With relationships\n$user = User::factory()->has(Product::factory()->count(3))->create();\n\n\u002F\u002F Sequences\nUser::factory()->count(3)->sequence(\n    ['role' => 'admin'], ['role' => 'editor'], ['role' => 'user'],\n)->create();\n```\n\n## Model Testing\n\n```php\nnamespace Tests\\Unit\\Models;\n\nuse App\\Models\\User;\nuse App\\Models\\Product;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Tests\\TestCase;\n\nclass UserTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_it_hides_sensitive_attributes(): void\n    {\n        $user = User::factory()->create();\n        $this->assertArrayNotHasKey('password', $user->toArray());\n    }\n\n    public function test_admin_scope_returns_only_admins(): void\n    {\n        User::factory()->admin()->create();\n        User::factory()->count(3)->create();\n\n        $this->assertCount(1, User::admin()->get());\n    }\n}\n\nclass ProductTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_active_scope_filters_correctly(): void\n    {\n        Product::factory()->count(3)->create(['is_active' => true]);\n        Product::factory()->count(2)->create(['is_active' => false]);\n\n        $this->assertCount(3, Product::active()->get());\n    }\n\n    public function test_it_belongs_to_a_user(): void\n    {\n        $user = User::factory()->create();\n        $product = Product::factory()->create(['user_id' => $user->id]);\n\n        $this->assertTrue($product->user->is($user));\n    }\n}\n```\n\n## Feature \u002F HTTP Testing\n\n```php\nnamespace Tests\\Feature\\Http\\Controllers;\n\nuse App\\Models\\Product;\nuse App\\Models\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Tests\\TestCase;\n\nclass ProductControllerTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_guests_are_redirected_to_login(): void\n    {\n        $this->get(route('products.create'))->assertRedirect(route('login'));\n    }\n\n    public function test_it_stores_a_new_product(): void\n    {\n        $user = User::factory()->create();\n        $this->actingAs($user);\n\n        $response = $this->post(route('products.store'), [\n            'name' => 'New Product',\n            'description' => 'Description',\n            'price' => 2999,\n            'stock' => 10,\n        ]);\n\n        $response->assertRedirect(route('products.index'));\n        $this->assertDatabaseHas('products', [\n            'name' => 'New Product',\n            'user_id' => $user->id,\n        ]);\n    }\n\n    public function test_it_validates_required_fields(): void\n    {\n        $this->actingAs(User::factory()->create());\n        $this->post(route('products.store'), [])\n            ->assertSessionHasErrors(['name', 'price']);\n    }\n\n    public function test_users_cannot_modify_others_products(): void\n    {\n        $owner = User::factory()->create();\n        $attacker = User::factory()->create();\n        $product = Product::factory()->create(['user_id' => $owner->id]);\n\n        $this->actingAs($attacker)\n            ->delete(route('products.destroy', $product))\n            ->assertForbidden();\n    }\n}\n```\n\n## JSON API Testing\n\n```php\nnamespace Tests\\Feature\\Http\\Controllers\\Api;\n\nuse App\\Models\\Product;\nuse App\\Models\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Tests\\TestCase;\n\nclass ProductApiTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_unauthenticated_requests_are_rejected(): void\n    {\n        $this->getJson('\u002Fapi\u002Fproducts')->assertUnauthorized();\n    }\n\n    public function test_it_lists_paginated_products(): void\n    {\n        $user = User::factory()->create();\n        Product::factory()->count(5)->create(['user_id' => $user->id]);\n\n        $response = $this->actingAs($user)->getJson('\u002Fapi\u002Fproducts');\n\n        $response->assertOk();\n        $response->assertJsonCount(5, 'data');\n        $response->assertJsonStructure([\n            'data' => [['id', 'name', 'price']],\n            'meta' => ['current_page', 'last_page', 'total'],\n        ]);\n    }\n\n    public function test_it_creates_a_product(): void\n    {\n        $user = User::factory()->create();\n\n        $response = $this->actingAs($user)->postJson('\u002Fapi\u002Fproducts', [\n            'name' => 'API Product',\n            'price' => 4999,\n        ]);\n\n        $response->assertCreated();\n        $response->assertJsonPath('data.name', 'API Product');\n    }\n\n    public function test_users_cannot_delete_others_products(): void\n    {\n        $owner = User::factory()->create();\n        $attacker = User::factory()->create();\n        $product = Product::factory()->create(['user_id' => $owner->id]);\n\n        $this->actingAs($attacker)\n            ->deleteJson(\"\u002Fapi\u002Fproducts\u002F{$product->id}\")\n            ->assertForbidden();\n    }\n}\n```\n\n## Sanctum API Auth Testing\n\n```php\nnamespace Tests\\Feature\\Http\\Controllers\\Api;\n\nuse App\\Models\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Illuminate\\Support\\Facades\\Hash;\nuse Tests\\TestCase;\n\nclass AuthControllerTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_users_can_register(): void\n    {\n        $response = $this->postJson('\u002Fapi\u002Fregister', [\n            'name' => 'Test User',\n            'email' => 'test@example.com',\n            'password' => 'Password123!',\n            'password_confirmation' => 'Password123!',\n        ]);\n\n        $response->assertCreated();\n        $response->assertJsonStructure(['data' => ['user', 'token']]);\n    }\n\n    public function test_users_can_login(): void\n    {\n        User::factory()->create([\n            'email' => 'test@example.com',\n            'password' => Hash::make('Password123!'),\n        ]);\n\n        $response = $this->postJson('\u002Fapi\u002Flogin', [\n            'email' => 'test@example.com',\n            'password' => 'Password123!',\n        ]);\n\n        $response->assertOk();\n        $response->assertJsonStructure(['data' => ['token']]);\n    }\n\n    public function test_users_cannot_login_with_wrong_password(): void\n    {\n        User::factory()->create(['email' => 'test@example.com']);\n\n        $this->postJson('\u002Fapi\u002Flogin', [\n            'email' => 'test@example.com',\n            'password' => 'wrong',\n        ])->assertUnprocessable();\n    }\n\n    public function test_token_bearer_authenticates_requests(): void\n    {\n        $user = User::factory()->create();\n        $token = $user->createToken('test')->plainTextToken;\n\n        $this->withToken($token)\n            ->getJson('\u002Fapi\u002Fuser')\n            ->assertOk()\n            ->assertJsonPath('data.email', $user->email);\n    }\n}\n```\n\n## Mocking and Fakes\n\n### HTTP Fake\n\n```php\nuse Illuminate\\Support\\Facades\\Http;\n\npublic function test_it_handles_successful_payment(): void\n{\n    Http::fake([\n        'api.stripe.com\u002F*' => Http::response(['id' => 'pi_123', 'status' => 'succeeded'], 200),\n    ]);\n\n    $result = (new PaymentService())->charge(2999);\n    $this->assertTrue($result->success);\n}\n\npublic function test_it_handles_gateway_failure(): void\n{\n    Http::fake([\n        'api.stripe.com\u002F*' => Http::response(['error' => 'card_declined'], 402),\n    ]);\n\n    $this->expectException(PaymentFailedException::class);\n    (new PaymentService())->charge(2999);\n}\n\npublic function test_it_retries_on_timeout(): void\n{\n    Http::fake([\n        'api.stripe.com\u002F*' => Http::sequence()\n            ->pushStatus(408)\n            ->pushStatus(200),\n    ]);\n\n    $this->assertTrue((new PaymentService())->charge(2999)->success);\n}\n```\n\n### Mail Fake\n\n```php\nMail::fake();\n\n$order->sendConfirmation();\n\nMail::assertSent(OrderConfirmation::class, function ($mail) use ($order) {\n    return $mail->hasTo($order->user->email);\n});\n```\n\n### Notification Fake\n\n```php\nNotification::fake();\n\n$user->notify(new WelcomeUser());\n\nNotification::assertSentTo($user, WelcomeUser::class);\n```\n\n### Queue Fake\n\n```php\nQueue::fake();\n\nProcessImage::dispatch($product);\n\nQueue::assertPushed(ProcessImage::class, function ($job) use ($product) {\n    return $job->product->id === $product->id;\n});\n```\n\n### Storage Fake\n\n```php\nStorage::fake('public');\n\n$file = UploadedFile::fake()->image('photo.jpg', 200, 200);\n\n$response = $this->actingAs($user)->post('\u002Favatar', [\n    'avatar' => $file,\n]);\n\n$response->assertSessionHasNoErrors();\nStorage::disk('public')->assertExists('avatars\u002F' . $file->hashName());\n```\n\n### Event Fake\n\n```php\nEvent::fake();\n\n$order->markAsShipped();\n\nEvent::assertDispatched(OrderShipped::class, function ($event) use ($order) {\n    return $event->order->id === $order->id;\n});\n```\n\n## Artisan Command Tests\n\n```php\npublic function test_it_sends_newsletters(): void\n{\n    Mail::fake();\n    User::factory()->count(5)->create(['subscribed' => true]);\n\n    $this->artisan('newsletter:send')\n        ->expectsOutput('Sending newsletter to 5 subscribers...')\n        ->assertExitCode(0);\n\n    Mail::assertSent(NewsletterMail::class, 5);\n}\n\npublic function test_it_handles_no_subscribers(): void\n{\n    $this->artisan('newsletter:send')\n        ->expectsOutput('No subscribers found.')\n        ->assertExitCode(0);\n}\n```\n\n## Authorization Tests\n\n```php\npublic function test_users_can_update_own_posts(): void\n{\n    $user = User::factory()->create();\n    $post = Post::factory()->create(['user_id' => $user->id]);\n\n    $this->actingAs($user)\n        ->put(route('posts.update', $post), ['title' => 'Updated'])\n        ->assertRedirect();\n}\n\npublic function test_users_cannot_update_others_posts(): void\n{\n    $post = Post::factory()->create();\n    $this->actingAs(User::factory()->create())\n        ->put(route('posts.update', $post), ['title' => 'Hacked'])\n        ->assertForbidden();\n}\n\npublic function test_gate_before_grants_super_admin_full_access(): void\n{\n    $super = User::factory()->create(['role' => 'super-admin']);\n    $post = Post::factory()->create();\n\n    $this->actingAs($super)\n        ->delete(route('posts.destroy', $post))\n        ->assertRedirect();\n\n    $this->assertSoftDeleted($post);\n}\n```\n\n## Pest Feature Tests\n\n```php\n\u003C?php\n\nuse App\\Models\\Product;\nuse App\\Models\\User;\n\nuses(\\Illuminate\\Foundation\\Testing\\RefreshDatabase::class);\n\nbeforeEach(function () {\n    $this->user = User::factory()->create();\n    $this->actingAs($this->user);\n});\n\nit('lists products', function () {\n    Product::factory()->count(3)->create(['user_id' => $this->user->id]);\n\n    $this->get(route('products.index'))\n        ->assertOk()\n        ->assertViewHas('products');\n});\n\nit('creates a product with valid data', function () {\n    $this->post(route('products.store'), [\n        'name' => 'Test Product', 'price' => 1999,\n    ])->assertRedirect();\n\n    $this->assertDatabaseHas('products', ['name' => 'Test Product']);\n});\n\nit('fails validation without required fields', function () {\n    $this->post(route('products.store'), [])\n        ->assertSessionHasErrors(['name', 'price']);\n});\n\nit('authorizes updates', function () {\n    $other = User::factory()->create();\n    $product = Product::factory()->create(['user_id' => $other->id]);\n\n    $this->put(route('products.update', $product), ['name' => 'Hacked'])\n        ->assertForbidden();\n});\n```\n\n## Coverage\n\n```bash\n# PHPUnit (use clover output for CI threshold checks)\nvendor\u002Fbin\u002Fphpunit --coverage-html coverage --coverage-clover clover.xml\n\n# Pest (built-in threshold support)\nvendor\u002Fbin\u002Fpest --coverage --min=80\n```\n\n### Coverage Goals\n\n| Component | Target |\n|-----------|--------|\n| Models | 95%+ |\n| Actions\u002FServices | 90%+ |\n| Form Requests | 90%+ |\n| Controllers | 85%+ |\n| Policies | 95%+ |\n| Overall | 80%+ |\n\n## Testing Best Practices\n\n### DO\n\n- Use factories over manual `create()` calls\n- One logical assertion per test\n- Descriptive names: `test_guests_cannot_create_products`\n- Test edge cases and authorization boundaries\n- Mock external services with `Http::fake()`, `Mail::fake()`\n- Use `RefreshDatabase` for clean state\n\n### DON'T\n\n- Don't test Laravel internals (trust the framework)\n- Don't make tests dependent on each other\n- Don't over-mock — mock only service boundaries\n- Don't test private methods — test through the public interface\n- Don't couple tests to HTML structure\n\n## Quick Reference\n\n| Pattern | Usage |\n|---------|-------|\n| `RefreshDatabase` | Reset database between tests |\n| `$this->actingAs($user)` | Authenticate as user |\n| `$this->withToken($token)` | Bearer token auth for APIs |\n| `Model::factory()->create()` | Create model with factory |\n| `Model::factory()->count(5)->create()` | Create multiple records |\n| `Http::fake([...])` | Mock HTTP calls |\n| `Mail::fake()` | Trap sent mail |\n| `Notification::fake()` | Trap sent notifications |\n| `Queue::fake()` | Trap queued jobs |\n| `Event::fake()` | Trap dispatched events |\n| `Storage::fake('public')` | Trap file operations |\n| `assertDatabaseHas` | Assert DB row exists |\n| `assertSoftDeleted` | Assert soft-delete |\n| `assertSessionHasErrors` | Assert validation errors |\n| `assertForbidden` | Assert 403 status |\n\n## Related Skills\n\n- `laravel-patterns` — Laravel architecture, Eloquent, routing, and API patterns\n- `laravel-security` — Laravel authentication, authorization, and secure coding\n- `tdd-workflow` — The repo-wide RED -> GREEN -> REFACTOR loop\n- `backend-patterns` — General backend API and database patterns\n","# Laravel Testing with TDD\n\nTest-driven development for Laravel applications using PHPUnit, Pest, Laravel factories, and testing helpers.\n\n## When to Activate\n\n- Writing new Laravel applications or features\n- Implementing API endpoints with Sanctum or Passport authentication\n- Testing Eloquent models, relationships, scopes, and accessors\n- Setting up testing infrastructure for Laravel projects\n- Writing feature tests for HTTP controllers and form requests\n- Mocking external services (queues, mail, notifications, HTTP)\n\n## TDD Workflow for Laravel\n\n### Red-Green-Refactor Cycle\n\n```php\n\u002F\u002F Step 1: RED — Write a failing test\npublic function test_a_product_can_be_created(): void\n{\n    $product = Product::factory()->create(['name' => 'Test Product']);\n    $this->assertDatabaseHas('products', ['name' => 'Test Product']);\n}\n\n\u002F\u002F Step 2: GREEN — Write the migration, model, and factory\n\u002F\u002F Step 3: REFACTOR — Improve while keeping tests green\n```\n\n## Setup\n\n### PHPUnit Configuration\n\n```xml\n\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003Cphpunit xmlns:xsi=\"http:\u002F\u002Fwww.w3.org\u002F2001\u002FXMLSchema-instance\"\n         xsi:noNamespaceSchemaLocation=\"vendor\u002Fphpunit\u002Fphpunit\u002Fphpunit.xsd\"\n         bootstrap=\"vendor\u002Fautoload.php\"\n         colors=\"true\">\n    \u003Ctestsuites>\n        \u003Ctestsuite name=\"Unit\">\n            \u003Cdirectory suffix=\"Test.php\">tests\u002FUnit\u003C\u002Fdirectory>\n        \u003C\u002Ftestsuite>\n        \u003Ctestsuite name=\"Feature\">\n            \u003Cdirectory suffix=\"Test.php\">tests\u002FFeature\u003C\u002Fdirectory>\n        \u003C\u002Ftestsuite>\n    \u003C\u002Ftestsuites>\n    \u003Cphp>\n        \u003Cenv name=\"APP_ENV\" value=\"testing\"\u002F>\n        \u003Cenv name=\"BCRYPT_ROUNDS\" value=\"4\"\u002F>\n        \u003Cenv name=\"CACHE_STORE\" value=\"array\"\u002F>\n        \u003Cenv name=\"DB_CONNECTION\" value=\"sqlite\"\u002F>\n        \u003Cenv name=\"DB_DATABASE\" value=\":memory:\"\u002F>\n        \u003Cenv name=\"MAIL_MAILER\" value=\"array\"\u002F>\n        \u003Cenv name=\"QUEUE_CONNECTION\" value=\"sync\"\u002F>\n        \u003Cenv name=\"SESSION_DRIVER\" value=\"array\"\u002F>\n    \u003C\u002Fphp>\n\u003C\u002Fphpunit>\n```\n\n### Base TestCase Setup\n\n```php\nnamespace Tests;\n\nuse Illuminate\\Foundation\\Testing\\TestCase as BaseTestCase;\n\nabstract class TestCase extends BaseTestCase\n{\n    protected function setUp(): void\n    {\n        parent::setUp();\n        \u002F\u002F Call $this->withoutExceptionHandling() only in tests that\n        \u002F\u002F test non-HTTP exceptions; it suppresses assertStatus() etc.\n    }\n\n    \u002F\u002F Helper: Authenticate and return user\n    protected function actingAsUser(): mixed\n    {\n        $user = \\App\\Models\\User::factory()->create();\n        $this->actingAs($user);\n        return $user;\n    }\n\n    protected function actingAsAdmin(): mixed\n    {\n        $admin = \\App\\Models\\User::factory()->admin()->create();\n        $this->actingAs($admin);\n        return $admin;\n    }\n}\n```\n\n## Model Factories\n\n```php\n\u002F\u002F database\u002Ffactories\u002FUserFactory.php\nclass UserFactory extends Factory\n{\n    protected static ?string $password = null;\n\n    public function definition(): array\n    {\n        return [\n            'name' => fake()->name(),\n            'email' => fake()->unique()->safeEmail(),\n            'email_verified_at' => now(),\n            'password' => static::$password ??= Hash::make('password'),\n            'remember_token' => Str::random(10),\n            'role' => 'user',\n        ];\n    }\n\n    public function admin(): static\n    {\n        return $this->state(fn (array $attributes) => ['role' => 'admin']);\n    }\n\n    public function unverified(): static\n    {\n        return $this->state(fn (array $attributes) => ['email_verified_at' => null]);\n    }\n}\n\n\u002F\u002F database\u002Ffactories\u002FProductFactory.php\nclass ProductFactory extends Factory\n{\n    public function definition(): array\n    {\n        return [\n            'name' => fake()->unique()->words(3, true),\n            'slug' => fn (array $attrs) => Str::slug($attrs['name']),\n            'description' => fake()->paragraph(),\n            'price' => fake()->numberBetween(100, 100000),\n            'stock' => fake()->numberBetween(0, 100),\n            'is_active' => true,\n            'user_id' => UserFactory::new(),\n        ];\n    }\n\n    public function outOfStock(): static\n    {\n        return $this->state(fn (array $attributes) => ['stock' => 0]);\n    }\n}\n```\n\n### Using Factories\n\n```php\n$user = User::factory()->create();\n$admin = User::factory()->admin()->create();\n$product = Product::factory()->create(['user_id' => $user->id]);\n$products = Product::factory()->count(10)->create();\n$draft = Product::factory()->make(); \u002F\u002F Not persisted\n\n\u002F\u002F With relationships\n$user = User::factory()->has(Product::factory()->count(3))->create();\n\n\u002F\u002F Sequences\nUser::factory()->count(3)->sequence(\n    ['role' => 'admin'], ['role' => 'editor'], ['role' => 'user'],\n)->create();\n```\n\n## Model Testing\n\n```php\nnamespace Tests\\Unit\\Models;\n\nuse App\\Models\\User;\nuse App\\Models\\Product;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Tests\\TestCase;\n\nclass UserTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_it_hides_sensitive_attributes(): void\n    {\n        $user = User::factory()->create();\n        $this->assertArrayNotHasKey('password', $user->toArray());\n    }\n\n    public function test_admin_scope_returns_only_admins(): void\n    {\n        User::factory()->admin()->create();\n        User::factory()->count(3)->create();\n\n        $this->assertCount(1, User::admin()->get());\n    }\n}\n\nclass ProductTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_active_scope_filters_correctly(): void\n    {\n        Product::factory()->count(3)->create(['is_active' => true]);\n        Product::factory()->count(2)->create(['is_active' => false]);\n\n        $this->assertCount(3, Product::active()->get());\n    }\n\n    public function test_it_belongs_to_a_user(): void\n    {\n        $user = User::factory()->create();\n        $product = Product::factory()->create(['user_id' => $user->id]);\n\n        $this->assertTrue($product->user->is($user));\n    }\n}\n```\n\n## Feature \u002F HTTP Testing\n\n```php\nnamespace Tests\\Feature\\Http\\Controllers;\n\nuse App\\Models\\Product;\nuse App\\Models\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Tests\\TestCase;\n\nclass ProductControllerTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_guests_are_redirected_to_login(): void\n    {\n        $this->get(route('products.create'))->assertRedirect(route('login'));\n    }\n\n    public function test_it_stores_a_new_product(): void\n    {\n        $user = User::factory()->create();\n        $this->actingAs($user);\n\n        $response = $this->post(route('products.store'), [\n            'name' => 'New Product',\n            'description' => 'Description',\n            'price' => 2999,\n            'stock' => 10,\n        ]);\n\n        $response->assertRedirect(route('products.index'));\n        $this->assertDatabaseHas('products', [\n            'name' => 'New Product',\n            'user_id' => $user->id,\n        ]);\n    }\n\n    public function test_it_validates_required_fields(): void\n    {\n        $this->actingAs(User::factory()->create());\n        $this->post(route('products.store'), [])\n            ->assertSessionHasErrors(['name', 'price']);\n    }\n\n    public function test_users_cannot_modify_others_products(): void\n    {\n        $owner = User::factory()->create();\n        $attacker = User::factory()->create();\n        $product = Product::factory()->create(['user_id' => $owner->id]);\n\n        $this->actingAs($attacker)\n            ->delete(route('products.destroy', $product))\n            ->assertForbidden();\n    }\n}\n```\n\n## JSON API Testing\n\n```php\nnamespace Tests\\Feature\\Http\\Controllers\\Api;\n\nuse App\\Models\\Product;\nuse App\\Models\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Tests\\TestCase;\n\nclass ProductApiTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_unauthenticated_requests_are_rejected(): void\n    {\n        $this->getJson('\u002Fapi\u002Fproducts')->assertUnauthorized();\n    }\n\n    public function test_it_lists_paginated_products(): void\n    {\n        $user = User::factory()->create();\n        Product::factory()->count(5)->create(['user_id' => $user->id]);\n\n        $response = $this->actingAs($user)->getJson('\u002Fapi\u002Fproducts');\n\n        $response->assertOk();\n        $response->assertJsonCount(5, 'data');\n        $response->assertJsonStructure([\n            'data' => [['id', 'name', 'price']],\n            'meta' => ['current_page', 'last_page', 'total'],\n        ]);\n    }\n\n    public function test_it_creates_a_product(): void\n    {\n        $user = User::factory()->create();\n\n        $response = $this->actingAs($user)->postJson('\u002Fapi\u002Fproducts', [\n            'name' => 'API Product',\n            'price' => 4999,\n        ]);\n\n        $response->assertCreated();\n        $response->assertJsonPath('data.name', 'API Product');\n    }\n\n    public function test_users_cannot_delete_others_products(): void\n    {\n        $owner = User::factory()->create();\n        $attacker = User::factory()->create();\n        $product = Product::factory()->create(['user_id' => $owner->id]);\n\n        $this->actingAs($attacker)\n            ->deleteJson(\"\u002Fapi\u002Fproducts\u002F{$product->id}\")\n            ->assertForbidden();\n    }\n}\n```\n\n## Sanctum API Auth Testing\n\n```php\nnamespace Tests\\Feature\\Http\\Controllers\\Api;\n\nuse App\\Models\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Illuminate\\Support\\Facades\\Hash;\nuse Tests\\TestCase;\n\nclass AuthControllerTest extends TestCase\n{\n    use RefreshDatabase;\n\n    public function test_users_can_register(): void\n    {\n        $response = $this->postJson('\u002Fapi\u002Fregister', [\n            'name' => 'Test User',\n            'email' => 'test@example.com',\n            'password' => 'Password123!',\n            'password_confirmation' => 'Password123!',\n        ]);\n\n        $response->assertCreated();\n        $response->assertJsonStructure(['data' => ['user', 'token']]);\n    }\n\n    public function test_users_can_login(): void\n    {\n        User::factory()->create([\n            'email' => 'test@example.com',\n            'password' => Hash::make('Password123!'),\n        ]);\n\n        $response = $this->postJson('\u002Fapi\u002Flogin', [\n            'email' => 'test@example.com',\n            'password' => 'Password123!',\n        ]);\n\n        $response->assertOk();\n        $response->assertJsonStructure(['data' => ['token']]);\n    }\n\n    public function test_users_cannot_login_with_wrong_password(): void\n    {\n        User::factory()->create(['email' => 'test@example.com']);\n\n        $this->postJson('\u002Fapi\u002Flogin', [\n            'email' => 'test@example.com',\n            'password' => 'wrong',\n        ])->assertUnprocessable();\n    }\n\n    public function test_token_bearer_authenticates_requests(): void\n    {\n        $user = User::factory()->create();\n        $token = $user->createToken('test')->plainTextToken;\n\n        $this->withToken($token)\n            ->getJson('\u002Fapi\u002Fuser')\n            ->assertOk()\n            ->assertJsonPath('data.email', $user->email);\n    }\n}\n```\n\n## Mocking and Fakes\n\n### HTTP Fake\n\n```php\nuse Illuminate\\Support\\Facades\\Http;\n\npublic function test_it_handles_successful_payment(): void\n{\n    Http::fake([\n        'api.stripe.com\u002F*' => Http::response(['id' => 'pi_123', 'status' => 'succeeded'], 200),\n    ]);\n\n    $result = (new PaymentService())->charge(2999);\n    $this->assertTrue($result->success);\n}\n\npublic function test_it_handles_gateway_failure(): void\n{\n    Http::fake([\n        'api.stripe.com\u002F*' => Http::response(['error' => 'card_declined'], 402),\n    ]);\n\n    $this->expectException(PaymentFailedException::class);\n    (new PaymentService())->charge(2999);\n}\n\npublic function test_it_retries_on_timeout(): void\n{\n    Http::fake([\n        'api.stripe.com\u002F*' => Http::sequence()\n            ->pushStatus(408)\n            ->pushStatus(200),\n    ]);\n\n    $this->assertTrue((new PaymentService())->charge(2999)->success);\n}\n```\n\n### Mail Fake\n\n```php\nMail::fake();\n\n$order->sendConfirmation();\n\nMail::assertSent(OrderConfirmation::class, function ($mail) use ($order) {\n    return $mail->hasTo($order->user->email);\n});\n```\n\n### Notification Fake\n\n```php\nNotification::fake();\n\n$user->notify(new WelcomeUser());\n\nNotification::assertSentTo($user, WelcomeUser::class);\n```\n\n### Queue Fake\n\n```php\nQueue::fake();\n\nProcessImage::dispatch($product);\n\nQueue::assertPushed(ProcessImage::class, function ($job) use ($product) {\n    return $job->product->id === $product->id;\n});\n```\n\n### Storage Fake\n\n```php\nStorage::fake('public');\n\n$file = UploadedFile::fake()->image('photo.jpg', 200, 200);\n\n$response = $this->actingAs($user)->post('\u002Favatar', [\n    'avatar' => $file,\n]);\n\n$response->assertSessionHasNoErrors();\nStorage::disk('public')->assertExists('avatars\u002F' . $file->hashName());\n```\n\n### Event Fake\n\n```php\nEvent::fake();\n\n$order->markAsShipped();\n\nEvent::assertDispatched(OrderShipped::class, function ($event) use ($order) {\n    return $event->order->id === $order->id;\n});\n```\n\n## Artisan Command Tests\n\n```php\npublic function test_it_sends_newsletters(): void\n{\n    Mail::fake();\n    User::factory()->count(5)->create(['subscribed' => true]);\n\n    $this->artisan('newsletter:send')\n        ->expectsOutput('Sending newsletter to 5 subscribers...')\n        ->assertExitCode(0);\n\n    Mail::assertSent(NewsletterMail::class, 5);\n}\n\npublic function test_it_handles_no_subscribers(): void\n{\n    $this->artisan('newsletter:send')\n        ->expectsOutput('No subscribers found.')\n        ->assertExitCode(0);\n}\n```\n\n## Authorization Tests\n\n```php\npublic function test_users_can_update_own_posts(): void\n{\n    $user = User::factory()->create();\n    $post = Post::factory()->create(['user_id' => $user->id]);\n\n    $this->actingAs($user)\n        ->put(route('posts.update', $post), ['title' => 'Updated'])\n        ->assertRedirect();\n}\n\npublic function test_users_cannot_update_others_posts(): void\n{\n    $post = Post::factory()->create();\n    $this->actingAs(User::factory()->create())\n        ->put(route('posts.update', $post), ['title' => 'Hacked'])\n        ->assertForbidden();\n}\n\npublic function test_gate_before_grants_super_admin_full_access(): void\n{\n    $super = User::factory()->create(['role' => 'super-admin']);\n    $post = Post::factory()->create();\n\n    $this->actingAs($super)\n        ->delete(route('posts.destroy', $post))\n        ->assertRedirect();\n\n    $this->assertSoftDeleted($post);\n}\n```\n\n## Pest Feature Tests\n\n```php\n\u003C?php\n\nuse App\\Models\\Product;\nuse App\\Models\\User;\n\nuses(\\Illuminate\\Foundation\\Testing\\RefreshDatabase::class);\n\nbeforeEach(function () {\n    $this->user = User::factory()->create();\n    $this->actingAs($this->user);\n});\n\nit('lists products', function () {\n    Product::factory()->count(3)->create(['user_id' => $this->user->id]);\n\n    $this->get(route('products.index'))\n        ->assertOk()\n        ->assertViewHas('products');\n});\n\nit('creates a product with valid data', function () {\n    $this->post(route('products.store'), [\n        'name' => 'Test Product', 'price' => 1999,\n    ])->assertRedirect();\n\n    $this->assertDatabaseHas('products', ['name' => 'Test Product']);\n});\n\nit('fails validation without required fields', function () {\n    $this->post(route('products.store'), [])\n        ->assertSessionHasErrors(['name', 'price']);\n});\n\nit('authorizes updates', function () {\n    $other = User::factory()->create();\n    $product = Product::factory()->create(['user_id' => $other->id]);\n\n    $this->put(route('products.update', $product), ['name' => 'Hacked'])\n        ->assertForbidden();\n});\n```\n\n## Coverage\n\n```bash\n# PHPUnit (use clover output for CI threshold checks)\nvendor\u002Fbin\u002Fphpunit --coverage-html coverage --coverage-clover clover.xml\n\n# Pest (built-in threshold support)\nvendor\u002Fbin\u002Fpest --coverage --min=80\n```\n\n### Coverage Goals\n\n| Component | Target |\n|-----------|--------|\n| Models | 95%+ |\n| Actions\u002FServices | 90%+ |\n| Form Requests | 90%+ |\n| Controllers | 85%+ |\n| Policies | 95%+ |\n| Overall | 80%+ |\n\n## Testing Best Practices\n\n### DO\n\n- Use factories over manual `create()` calls\n- One logical assertion per test\n- Descriptive names: `test_guests_cannot_create_products`\n- Test edge cases and authorization boundaries\n- Mock external services with `Http::fake()`, `Mail::fake()`\n- Use `RefreshDatabase` for clean state\n\n### DON'T\n\n- Don't test Laravel internals (trust the framework)\n- Don't make tests dependent on each other\n- Don't over-mock — mock only service boundaries\n- Don't test private methods — test through the public interface\n- Don't couple tests to HTML structure\n\n## Quick Reference\n\n| Pattern | Usage |\n|---------|-------|\n| `RefreshDatabase` | Reset database between tests |\n| `$this->actingAs($user)` | Authenticate as user |\n| `$this->withToken($token)` | Bearer token auth for APIs |\n| `Model::factory()->create()` | Create model with factory |\n| `Model::factory()->count(5)->create()` | Create multiple records |\n| `Http::fake([...])` | Mock HTTP calls |\n| `Mail::fake()` | Trap sent mail |\n| `Notification::fake()` | Trap sent notifications |\n| `Queue::fake()` | Trap queued jobs |\n| `Event::fake()` | Trap dispatched events |\n| `Storage::fake('public')` | Trap file operations |\n| `assertDatabaseHas` | Assert DB row exists |\n| `assertSoftDeleted` | Assert soft-delete |\n| `assertSessionHasErrors` | Assert validation errors |\n| `assertForbidden` | Assert 403 status |\n\n## Related Skills\n\n- `laravel-patterns` — Laravel architecture, Eloquent, routing, and API patterns\n- `laravel-security` — Laravel authentication, authorization, and secure coding\n- `tdd-workflow` — The repo-wide RED -> GREEN -> REFACTOR loop\n- `backend-patterns` — General backend API and database patterns\n",{"name":5,"metadata":24,"description":7},{"origin":25},"ECC","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fecc\u002Flaravel-tdd","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill laravel-tdd",{"tool":38,"command":39},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill laravel-tdd",{"tool":41,"command":42},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill laravel-tdd","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fecc\u002Flaravel-tdd\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]