| name | test-driven-development |
| description | Ciclo RED-GREEN-REFACTOR obrigatorio para todo codigo de producao |
| triggers | ["implementar","codigo","desenvolver","tdd","feature"] |
| globs | ["**/*.test.*","**/*.spec.*","tests/**"] |
| steps | 3 |
| checkpoints | ["red_phase_complete","green_phase_complete","refactor_phase_complete"] |
| requires_validation | true |
Test-Driven Development Skill
Metadata
- Total de Steps: 3 (RED, GREEN, REFACTOR)
- Ciclo: Repetir para cada unidade de funcionalidade
- Prerequisito: Plano de implementacao aprovado
Principio Fundamental
NUNCA escreva codigo de producao sem um teste que falhe primeiro.
Codigo sem teste = Divida Tecnica = BLOQUEADO
Safe-Guard: Protecao de Dados
[!CRITICAL]
SEGURANCA EM PRIMEIRO LUGAR
Validacoes Obrigatorias Antes de Qualquer Operacao
validation_check "safe_path" "$filepath"
validation_check "file_exists" "$filepath"
validation_check "tests_pass"
Regras de Seguranca
- Snapshots: Execute
aidev snapshot antes de mudancas estruturais
- Double-Check: Antes de deletar, listar exatamente o que sera removido
- Isolamento: NUNCA execute
rm -rf em paths genericos
- Confirmacao: Se houver risco de perda de dados, PARE e peca confirmacao
Step 1: RED Phase
Checkpoint: red_phase_complete
Objetivo
Escrever um teste que FALHE pelo motivo correto.
Acoes
- Identificar a menor unidade de funcionalidade a implementar
- Escrever o teste ANTES do codigo
- Executar o teste - DEVE FALHAR
- Verificar que falha pelo motivo esperado (nao por erro de sintaxe)
Template de Teste
describe('[Feature/Component]', () => {
it('should [comportamento esperado] when [condicao]', () => {
const input = ...;
const result = funcaoATestar(input);
expect(result).toBe(expected);
});
});
Criterios de Validacao
Comando de Verificacao
npm test -- --testNamePattern="[nome do teste]"
pytest -k "[nome do teste]"
php artisan test --filter="[nome do teste]"
Confianca
- Se teste passa antes de escrever codigo:
confidence: 0.1 (algo errado)
- Se teste falha pelo motivo certo:
confidence: 0.9 (prosseguir)
Step 2: GREEN Phase
Checkpoint: green_phase_complete
Objetivo
Escrever o MINIMO codigo necessario para o teste passar.
Acoes
- Implementar APENAS o necessario para o teste passar
- Nao adicionar features extras
- Nao otimizar prematuramente
- Executar o teste - DEVE PASSAR
Principios
- YAGNI: You Aren't Gonna Need It
- Minimal: Menos codigo possivel
- Focused: Apenas o que o teste exige
Criterios de Validacao
Comando de Verificacao
npm test -- --testNamePattern="[nome do teste]"
npm test
Confianca
- Se teste passa e nenhuma regressao:
confidence: 0.95
- Se outros testes quebraram:
confidence: 0.2 (investigar)
Step 3: REFACTOR Phase
Checkpoint: refactor_phase_complete
Objetivo
Melhorar a qualidade do codigo SEM mudar comportamento.
Pre-Condicoes
validation_check "tests_pass"
aidev snapshot
Acoes
- Identificar oportunidades de melhoria:
- Nomes mais claros
- Extracao de funcoes
- Remocao de duplicacao (se >= 3 ocorrencias)
- Simplificacao de logica
- Fazer UMA melhoria por vez
- Executar testes apos CADA mudanca
- Se teste falhar, reverter imediatamente
Criterios de Validacao
Comando de Verificacao
npm test
git diff --stat
Anti-Patterns a Evitar
1. Test After Implementation
ERRADO: Escrever codigo -> Escrever teste
CERTO: Escrever teste -> Escrever codigo
2. Testing Implementation Details
ERRADO: expect(spy.toHaveBeenCalledWith(...))
CERTO: expect(result).toBe(expected)
3. Testes Que Sempre Passam
ERRADO: Sem assertions, catch-all de excecoes
CERTO: Assertions especificas que podem falhar
4. Flaky Tests
ERRADO: Dependem de timing, estado externo
CERTO: Isolados, deterministicos
5. Testing the Framework
ERRADO: Testar que React renderiza
CERTO: Testar SUA logica de componente
Estrutura de Teste por Stack
JavaScript/TypeScript (Jest/Vitest)
describe('Feature', () => {
beforeEach(() => { });
afterEach(() => { });
it('should do X when Y', () => {
});
});
PHP (PHPUnit/Pest)
test('feature does X when Y', function () {
$input = ...;
$result = $this->feature->execute($input);
expect($result)->toBe($expected);
});
Python (pytest)
def test_feature_does_x_when_y():
input_data = ...
result = feature(input_data)
assert result == expected
Metas de Cobertura
| Tipo | Meta | Foco |
|---|
| Unit Tests | 80%+ | Funcoes individuais |
| Integration | Paths criticos | Interacao entre modulos |
| E2E | Happy paths + erros | Fluxos completos do usuario |
Transicoes
Ciclo Completo
RED -> GREEN -> REFACTOR -> [proxima feature] -> RED -> ...
Ao Completar Feature
- Todos os testes passando
- Cobertura adequada
- Codigo refatorado
- Commit atomico
Handoff
skill_complete "test-driven-development"
agent_handoff "backend" "qa" "Revisar implementacao" "src/feature.ts"
Exemplo de Uso com Orquestrador
skill_init "test-driven-development"
skill_set_steps "test-driven-development" 3
skill_advance "test-driven-development" "RED: Escrever teste que falha"
validation_log "test_fails" "tests/feature.test.ts" "passed"
skill_validate_checkpoint "test-driven-development"
skill_advance "test-driven-development" "GREEN: Implementar minimo"
validation_check "tests_pass"
skill_validate_checkpoint "test-driven-development"
skill_advance "test-driven-development" "REFACTOR: Melhorar qualidade"
validation_check "tests_pass"
skill_validate_checkpoint "test-driven-development"
skill_complete "test-driven-development"
Ferramentas por Stack
| Stack | Test Runner | Coverage | Mocking |
|---|
| JavaScript | Jest, Vitest | c8, istanbul | jest.mock |
| TypeScript | Jest, Vitest | c8 | ts-jest |
| PHP | PHPUnit, Pest | xdebug | Mockery |
| Python | pytest | coverage.py | pytest-mock |
| Go | testing | go test -cover | testify |
| Laravel | Pest, PHPUnit | xdebug | Mockery |
| React | RTL, Vitest | c8 | MSW |