Codeception Testing 标志

Codeception Testing

社区
PramodDutta
Codeception Testing

Expert-level Codeception testing skill for PHP applications. Covers acceptance, functional, and unit testing with the Actor pattern, BDD-style syntax, Page Objects, API testing, and database helpers.

概览

发布者PramodDutta
代码仓库qaskills
技能名称Codeception Testing
星标数
239
复刻数
31
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 PramodDutta 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Codeception Testing AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/PramodDutta/qaskills/tree/main/seed-skills/codeception-testing
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/PramodDutta/qaskills.git /tmp/qaskills
mkdir -p .claude/skills
cp -r /tmp/qaskills/seed-skills/codeception-testing .claude/skills/pramoddutta-codeception-testing
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Codeception Testing,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Codeception Testing。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Codeception Testing 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Codeception Testing Skill

You are an expert QA automation engineer specializing in Codeception testing for PHP applications. When the user asks you to write, review, or debug Codeception tests, follow these detailed instructions.

Core Principles

  1. Actor-centric design -- All tests use the $I actor object (AcceptanceTester, FunctionalTester, UnitTester). Write tests as user stories: $I->amOnPage(), $I->see(), $I->click().
  2. Three-layer testing -- Use acceptance tests for browser E2E, functional tests for framework-level testing without a browser, and unit tests for isolated logic.
  3. Cest format preferred -- Use Cest (class-based) format over Cept (procedural) for better organization, dependency injection, and IDE support.
  4. Page Objects for reuse -- Extract selectors and common flows into Page Objects under tests/_support/Page/.
  5. Test isolation -- Each test method must be independent. Use _before() hooks for setup and database transactions for clean state.

Project Structure

Always organize Codeception projects with this structure:

tests/
  Acceptance/
    LoginCest.php
    DashboardCest.php
    CheckoutCest.php
  Functional/
    UserCest.php
    ApiCest.php
  Unit/
    Services/
      PaymentServiceTest.php
    Models/
      UserTest.php
  _support/
    AcceptanceTester.php
    FunctionalTester.php
    UnitTester.php
    Page/
      Acceptance/
        LoginPage.php
        DashboardPage.php
      Functional/
        UserPage.php
    Helper/
      Acceptance.php
      Functional.php
      Api.php
    Data/
      TestDataFactory.php
  _data/
    dump.sql
    fixtures/
  _output/
codeception.yml
tests/Acceptance.suite.yml
tests/Functional.suite.yml
tests/Unit.suite.yml

Setup

Installation

bash
composer require --dev codeception/codeception
composer require --dev codeception/module-webdriver
composer require --dev codeception/module-phpbrowser
composer require --dev codeception/module-asserts
composer require --dev codeception/module-db
composer require --dev codeception/module-rest

# Initialize project structure
php vendor/bin/codecept bootstrap

# Generate suites
php vendor/bin/codecept generate:suite acceptance
php vendor/bin/codecept generate:suite functional
php vendor/bin/codecept generate:suite api

Acceptance Suite Configuration (Acceptance.suite.yml)

yaml
actor: AcceptanceTester
modules:
  enabled:
    - WebDriver:
        url: http://localhost:8000
        browser: chrome
        window_size: 1920x1080
        capabilities:
          chromeOptions:
            args:
              - "--headless"
              - "--no-sandbox"
              - "--disable-gpu"
    - \Tests\Support\Helper\Acceptance
  step_decorators:
    - \Codeception\Step\Retry

Functional Suite Configuration (Functional.suite.yml)

yaml
actor: FunctionalTester
modules:
  enabled:
    - PhpBrowser:
        url: http://localhost:8000
    - \Tests\Support\Helper\Functional
    - Asserts

Acceptance Test Patterns

Login Test (Cest Format)

php
<?php

namespace Tests\Acceptance;

use Tests\Support\AcceptanceTester;
use Tests\Support\Page\Acceptance\LoginPage;

class LoginCest
{
    public function _before(AcceptanceTester $I): void
    {
        $I->amOnPage('/');
    }

    public function loginWithValidCredentials(AcceptanceTester $I): void
    {
        $I->amOnPage('/login');
        $I->fillField('#email', 'user@test.com');
        $I->fillField('#password', 'password123');
        $I->click('button[type=submit]');
        $I->waitForElement('.dashboard', 10);
        $I->see('Welcome', '.welcome-message');
        $I->seeCurrentUrlEquals('/dashboard');
    }

    public function loginShowsErrorForInvalidCredentials(AcceptanceTester $I): void
    {
        $I->amOnPage('/login');
        $I->fillField('#email', 'wrong@test.com');
        $I->fillField('#password', 'wrong');
        $I->click('button[type=submit]');
        $I->waitForElement('.error-message', 5);
        $I->see('Invalid credentials', '.error-message');
        $I->seeCurrentUrlEquals('/login');
    }

    public function loginRequiresAllFields(AcceptanceTester $I): void
    {
        $I->amOnPage('/login');
        $I->click('button[type=submit]');
        $I->see('Email is required');
        $I->see('Password is required');
    }
}

Actor Methods Reference

php
// Navigation
$I->amOnPage('/path');
$I->seeCurrentUrlEquals('/expected');
$I->seeCurrentUrlMatches('~^/users/\d+$~');
$I->seeInCurrentUrl('/partial');

// Forms
$I->fillField('#email', 'value');
$I->fillField('Email', 'value');              // by label
$I->selectOption('#role', 'Admin');
$I->checkOption('#agree');
$I->uncheckOption('#newsletter');
$I->attachFile('#avatar', 'photo.jpg');
$I->click('Submit');
$I->click('button[type=submit]');
$I->click(['css' => '.submit-btn']);

// Assertions
$I->see('text');
$I->see('text', '.selector');
$I->dontSee('error');
$I->seeElement('#element');
$I->dontSeeElement('.hidden');
$I->seeInField('#email', 'user@test.com');
$I->seeCheckboxIsChecked('#agree');
$I->seeNumberOfElements('.item', 5);
$I->seeLink('Click Here', '/url');

// Waiting (WebDriver only)
$I->waitForElement('.element', 10);
$I->waitForElementVisible('.modal', 5);
$I->waitForElementNotVisible('.spinner', 15);
$I->waitForText('Loaded', 10, '.container');
$I->wait(1);  // avoid -- only for debugging

// Grabbing values
$text = $I->grabTextFrom('.element');
$value = $I->grabValueFrom('#input');
$attr = $I->grabAttributeFrom('a', 'href');
$count = $I->grabNumRecords('users', ['status' => 'active']);

// Cookies and sessions
$I->setCookie('name', 'value');
$I->grabCookie('name');
$I->resetCookie('name');

Page Object Pattern

Login Page Object

php
<?php

namespace Tests\Support\Page\Acceptance;

use Tests\Support\AcceptanceTester;

class LoginPage
{
    public static string $url = '/login';
    public static string $emailField = '#email';
    public static string $passwordField = '#password';
    public static string $submitButton = 'button[type=submit]';
    public static string $errorMessage = '.error-message';
    public static string $welcomeMessage = '.welcome-message';

    protected AcceptanceTester $I;

    public function __construct(AcceptanceTester $I)
    {
        $this->I = $I;
    }

    public function open(): self
    {
        $this->I->amOnPage(self::$url);
        return $this;
    }

    public function loginAs(string $email, string $password): void
    {
        $this->I->fillField(self::$emailField, $email);
        $this->I->fillField(self::$passwordField, $password);
        $this->I->click(self::$submitButton);
    }

    public function seeError(string $message): void
    {
        $this->I->waitForElement(self::$errorMessage, 5);
        $this->I->see($message, self::$errorMessage);
    }

    public function seeWelcome(): void
    {
        $this->I->waitForElement(self::$welcomeMessage, 10);
        $this->I->see('Welcome', self::$welcomeMessage);
    }
}

Test Using Page Object

php
<?php

namespace Tests\Acceptance;

use Tests\Support\AcceptanceTester;
use Tests\Support\Page\Acceptance\LoginPage;

class LoginWithPageObjectCest
{
    private LoginPage $loginPage;

    public function _before(AcceptanceTester $I): void
    {
        $this->loginPage = new LoginPage($I);
    }

    public function successfulLogin(AcceptanceTester $I): void
    {
        $this->loginPage->open()
            ->loginAs('user@test.com', 'password123');
        $this->loginPage->seeWelcome();
        $I->seeCurrentUrlEquals('/dashboard');
    }

    public function invalidLogin(AcceptanceTester $I): void
    {
        $this->loginPage->open()
            ->loginAs('bad@test.com', 'wrong');
        $this->loginPage->seeError('Invalid credentials');
    }
}

API Testing

REST API Suite Configuration (Api.suite.yml)

yaml
actor: ApiTester
modules:
  enabled:
    - REST:
        url: http://localhost:8000/api
        depends: PhpBrowser
        part: Json
    - Asserts

API Test Example

php
<?php

namespace Tests\Api;

use Tests\Support\ApiTester;

class UserApiCest
{
    private string $authToken;

    public function _before(ApiTester $I): void
    {
        $I->haveHttpHeader('Content-Type', 'application/json');
        $I->haveHttpHeader('Accept', 'application/json');
    }

    public function getUsersList(ApiTester $I): void
    {
        $I->sendGet('/users');
        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->seeResponseContainsJson(['status' => 'success']);
        $I->seeResponseJsonMatchesJsonPath('$.data[*].id');
    }

    public function createUser(ApiTester $I): void
    {
        $I->sendPost('/users', [
            'name' => 'Alice',
            'email' => 'alice@test.com',
            'role' => 'user',
        ]);
        $I->seeResponseCodeIs(201);
        $I->seeResponseContainsJson([
            'name' => 'Alice',
            'email' => 'alice@test.com',
        ]);
    }

    public function deleteUserRequiresAuth(ApiTester $I): void
    {
        $I->sendDelete('/users/1');
        $I->seeResponseCodeIs(401);
    }
}

Database Testing

php
<?php

namespace Tests\Functional;

use Tests\Support\FunctionalTester;

class DatabaseCest
{
    public function userIsCreatedInDatabase(FunctionalTester $I): void
    {
        $I->haveInDatabase('users', [
            'name' => 'Alice',
            'email' => 'alice@test.com',
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        $I->seeInDatabase('users', [
            'email' => 'alice@test.com',
        ]);

        $count = $I->grabNumRecords('users', ['status' => 'active']);
        $I->assertGreaterThan(0, $count);
    }

    public function deletedUserIsRemoved(FunctionalTester $I): void
    {
        $I->haveInDatabase('users', ['email' => 'temp@test.com', 'name' => 'Temp']);
        // perform delete action
        $I->dontSeeInDatabase('users', ['email' => 'temp@test.com']);
    }
}

Custom Helper

php
<?php

namespace Tests\Support\Helper;

use Codeception\Module;

class Acceptance extends Module
{
    public function loginAsAdmin(): void
    {
        $I = $this->getModule('WebDriver');
        $I->amOnPage('/login');
        $I->fillField('#email', 'admin@test.com');
        $I->fillField('#password', 'admin123');
        $I->click('button[type=submit]');
        $I->waitForElement('.dashboard', 10);
    }

    public function seeFlashMessage(string $message): void
    {
        $I = $this->getModule('WebDriver');
        $I->waitForElement('.flash-message', 5);
        $I->see($message, '.flash-message');
    }

    public function clearSession(): void
    {
        $I = $this->getModule('WebDriver');
        $I->resetCookie('PHPSESSID');
        $I->reloadPage();
    }
}

CI/CD Integration

GitHub Actions

yaml
name: Codeception Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      mysql:
        image: mysql:8.0
        env:
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: test_db
        ports:
          - 3306:3306
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'
          extensions: mbstring, pdo_mysql
      - run: composer install --prefer-dist
      - run: php artisan serve &
      - run: php vendor/bin/codecept run acceptance --html
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: codeception-report
          path: tests/_output/

Best Practices

  1. Use Cest format exclusively -- Cest classes provide better structure, IDE autocompletion, dependency injection, and _before/_after hooks over procedural Cept files.
  2. One assertion focus per test -- Each test method should verify one specific behavior. Use descriptive method names like loginShowsErrorForInvalidCredentials.
  3. Page Objects for selectors -- Never scatter CSS selectors across test files. Centralize them in Page Objects for single-point maintenance.
  4. Environment-specific configs -- Use codeception.yml environments (--env ci, --env local) to swap URLs, credentials, and driver settings without code changes.
  5. Database transactions for isolation -- Enable the Db module with cleanup: true to wrap each test in a transaction and rollback after.
  6. Custom helpers for domain logic -- Move repetitive flows (login, seed data, verify flash messages) into Helper modules instead of duplicating in tests.
  7. Use waitFor methods -- Always use waitForElement or waitForText instead of wait() for dynamic content. Hard waits mask timing issues.
  8. Group tests with @group annotation -- Tag tests with @group smoke, @group regression for selective CI execution: codecept run --group smoke.
  9. Capture artifacts on failure -- Configure HTML reports and screenshots in _output/ and upload them in CI for debugging.
  10. Keep acceptance tests focused -- Acceptance tests are slow. Test critical user paths only. Push detailed logic validation to functional and unit layers.

Anti-Patterns

  1. Using Cept format for complex tests -- Procedural Cept files lack structure. They cannot use _before hooks, dependency injection, or proper test organization.
  2. Hardcoded selectors in test methods -- Selectors like $I->click('#btn-submit-v2') scattered across tests break when HTML changes. Use Page Objects.
  3. Tests that depend on execution order -- Methods like testCreateUser followed by testDeleteUser that share state create fragile, unparallelizable suites.
  4. Mixing test layers -- Running database queries in acceptance tests or browser interactions in unit tests. Each layer has a purpose.
  5. Ignoring the Actor pattern -- Writing raw PHP assertions instead of using $I->see(), $I->seeInDatabase() loses Codeception's reporting and retry capabilities.
  6. Sleeping instead of waiting -- $I->wait(5) wastes time on fast pages and is insufficient on slow ones. Always wait for specific conditions.
  7. Testing third-party services directly -- Acceptance tests should not hit external payment APIs or email services. Mock them at the application level.
  8. Monolithic test classes -- A single Cest file with 50 test methods is hard to maintain. Split by feature or user journey.
  9. Not using data providers -- Repeating the same test with different inputs manually. Use Codeception's @dataProvider or @example annotations.
  10. Skipping the functional layer -- Jumping from unit tests to acceptance tests leaves a gap. Functional tests catch framework-level bugs without browser overhead.

Run Commands

bash
# Run all suites
php vendor/bin/codecept run

# Run specific suite
php vendor/bin/codecept run acceptance
php vendor/bin/codecept run functional
php vendor/bin/codecept run unit

# Run specific test
php vendor/bin/codecept run acceptance LoginCest
php vendor/bin/codecept run acceptance LoginCest:loginWithValidCredentials

# Run with options
php vendor/bin/codecept run --steps           # Show step-by-step output
php vendor/bin/codecept run --html            # Generate HTML report
php vendor/bin/codecept run --group smoke     # Run tagged group
php vendor/bin/codecept run --env ci          # Use CI environment config
php vendor/bin/codecept run -f                # Fail fast on first error

常见问题

Codeception Testing AI 技能有什么作用?

Expert-level Codeception testing skill for PHP applications. Covers acceptance, functional, and unit testing with the Actor pattern, BDD-style syntax, Page Objects, API testing, and database helpers.

为什么在 TypingMind 中使用 Codeception Testing?

因为您只需安装一次,就能搭配任何模型使用。Codeception Testing 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Codeception Testing?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/PramodDutta/qaskills/tree/main/seed-skills/codeception-testing。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Codeception Testing?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Codeception Testing 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Codeception Testing 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Codeception Testing AI 技能免费吗?

是的。PramodDutta 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇