Logo de Drupal Testing

Drupal Testing

Comunidade
grasmash
drupal-testing

Test-driven development for Drupal with PHPUnit and Drupal Test Traits (DTT). Use when writing or fixing tests, reproducing a bug before fixing it, choosing a bootstrap level (Unit vs Kernel vs ExistingSite/functional), testing permission gates, or debugging tests that silently run zero assertions. Covers the bug-fix RED-first discipline, bootstrap cost tradeoffs, the anonymous-403 permission trap, and the PHPUnit-version pin that makes Drupal tests pass vacuously.

Visão geral

Publicado porgrasmash
Repositóriodrupal-claude-skills
Nome da habilidadedrupal-testing
Estrelas
77
Forks
4
Arquivos incluídos
Somente instruções
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Completa em si mesma

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por grasmash no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Drupal Testing no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/grasmash/drupal-claude-skills/tree/main/skills/drupal-testing
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/grasmash/drupal-claude-skills.git /tmp/drupal-claude-skills
mkdir -p .claude/skills
cp -r /tmp/drupal-claude-skills/skills/drupal-testing .claude/skills/drupal-testing
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Drupal Testing em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Drupal Testing automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Drupal Testing não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Drupal Testing (TDD)

Hard-won testing discipline for Drupal. Pairs with the test-writer and test-runner agents — this skill is the how, those agents are the who.

Bug-fix TDD — the RED step is non-negotiable

Every bug fix follows this exact sequence. Skipping step 2 is what makes "fixed" bugs come back.

  1. Write a test that reproduces the bug — exercise the real code path the user hits, not a paraphrase of the suspected logic.
  2. Run it and assert it FAILS, with the symptom matching the report. If it doesn't fail, you haven't reproduced the bug — keep digging until it fails for the right reason. The red-to-green transition is your only proof the test actually exercises the bug; without it, you can't tell whether the test catches the bug or just happens to pass on green.
  3. Fix the production code.
  4. Re-run the same test and assert it now passes.

Pick the lightest bootstrap that fits — it dominates cost

Drupal test base classes differ in bootstrap cost by orders of magnitude. Default to the cheapest one that can express the assertion.

Base classBootstrapUse for
UnitTestCasenone (pure PHP)isolated logic, no Drupal services
KernelTestBaseminimal; declare deps in protected static $modulesservices / business logic in isolation
ExistingSite (DTT ExistingSiteBase)runs against the served site (real config, contrib, field storage)flows that need the full installed site
Functional/BrowserTestBasefull reinstall per testlast resort; very slow

Prefer Unit and Kernel where the logic doesn't need the full site — they're far faster. Within ExistingSite, the cost is not bootstrap; it's drupalLogin() + drupalGet() (real HTTP, ~25s each). Before adding those, ask whether the assertion is about HTTP/auth/redirects or about rendered output:

  • Service logic → call \Drupal::service(...)->method() directly. No HTTP.
  • Template render → build the render array, call \Drupal::service('renderer')->renderInIsolation($build). No HTTP.
  • Entity render → DTT's EntityCrawlerTrait::getRenderedEntityCrawler($entity, $view_mode). No HTTP.
  • Controller wiring, auth, redirects → drupalLogin + drupalGet. Keep to one smoke test per feature.

Data providers multiply cost: an 11-row matrix × drupalLogin + drupalGet ≈ 5 minutes. Split into a fast service/render matrix plus a single HTTP smoke test.

The anonymous-403 permission trap

A "returns 403 for anonymous" test does not prove a route's _permission is enforced. Two ways it lies:

  1. A route gated with both _user_is_logged_in: TRUE and _permission rejects anonymous on the login gate first — so deleting _permission entirely still passes the anonymous test.
  2. When the gating permission sits on the authenticated role, no logged-in user can ever be denied, so the gate is effectively open.

_permission syntax: + is OR, , is AND.

To actually test the gate, do one of:

  • Log in a user who genuinely lacks the permission and assert 403, or
  • Pin the gate at the route-definition level: assert $route->getRequirement('_permission') equals the expected string, so loosening the gate fails a test.

TDD the guard: strip the permission → confirm RED → restore.

Tests that pass vacuously (the silent-zero trap)

If a whole class of tests suddenly "passes" while running 0 assertions, suspect a PHPUnit-version mismatch, not green code.

  • Drupal core supports a specific PHPUnit major. A wrong pin (e.g. PHPUnit 12 against a core that only supports 11) makes every test extending a Drupal base class (UnitTestCase/KernelTestBase) collect zero tests and exit 0 — there's no compatibility shim, so collection fatals silently. Meanwhile plain \PHPUnit\Framework\TestCase + DTT ExistingSite tests still run, masking the breakage.
  • PHPUnit 10+ uses PHP 8 attributes (#[Group('x')]), not @group docblock annotations. --exclude-group/--group won't match legacy annotations — migrate to attributes.
  • Sanity check: a passing test run should report a non-trivial assertion count. OK (0 tests, 0 assertions) for a suite you know has tests means the runner isn't collecting them.

Verify the real code path locally — passing unit tests aren't enough

For any change to runtime behavior (cron jobs, drush commands, data processing, API endpoints, service logic), execute the changed code path locally and confirm the real-world outcome before declaring it done — don't stop at green unit tests. Run the actual command/service (e.g. via DDEV: ddev drush <command>), then check the resulting state (DB rows, updated field values, emitted output). This catches what tests miss: environment differences, data-dependent bugs, and integration failures across the real installed site. Unit/Kernel tests prove the logic in isolation; only running it proves the wiring.

CI: fix failing tests locally, not by re-pushing

When CI fails on test errors, don't iterate by pushing commits and re-running the full suite (often ~20 min/run):

  1. Identify the failing tests from CI logs.
  2. Reproduce locally (vendor/bin/phpunit --filter Class::method path/to/Test.php).
  3. Fix and run each test individually until green.
  4. Commit.
  5. Only then re-run the full CI suite.

phpcs in test files

  • Section-divider comments (// ---) before a docblock violate both CommentEmptyLine.SpacingAfter and FunctionSpacing.Before. Don't use them in test files.
  • Run vendor/bin/phpcbf <file> to auto-fix before recommitting.

Perguntas frequentes

O que a habilidade de IA Drupal Testing faz?

Test-driven development for Drupal with PHPUnit and Drupal Test Traits (DTT). Use when writing or fixing tests, reproducing a bug before fixing it, choosing a bootstrap level (Unit vs Kernel vs ExistingSite/functional), testing permission gates, or debugging tests that silently run zero assertions. Covers the bug-fix RED-first discipline, bootstrap cost tradeoffs, the anonymous-403 permission trap, and the PHPUnit-version pin that makes Drupal tests pass vacuously.

Por que usar Drupal Testing no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Drupal Testing é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Drupal Testing no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/grasmash/drupal-claude-skills/tree/main/skills/drupal-testing. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Drupal Testing?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Drupal Testing?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Drupal Testing com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Drupal Testing é gratuita?

A habilidade é publicada no GitHub por grasmash. Consulte os termos de licenciamento no repositório. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇