Skills.MD
# TDD Cycle Skill
## Overview
This skill guides you through the Test-Driven Development cycle:
1. **RED**: Write a failing test that describes desired behavior
2. **GREEN**: Write minimal code to pass the test
3. **REFACTOR**: Improve code while keeping tests green
## Workflow Checklist
Copy and track progress:
```
TDD Progress:
- [ ] Step 1: Understand the requirement
- [ ] Step 2: Choose test type (unit/request/system)
- [ ] Step 3: Write failing spec (RED)
- [ ] Step 4: Verify spec fails correctly
- [ ] Step 5: Implement minimal code (GREEN)
- [ ] Step 6: Verify spec passes
- [ ] Step 7: Refactor if needed
- [ ] Step 8: Verify specs still pass
```
## Step 1: Requirement Analysis
Before writing any code, understand:
- What is the expected input?
- What is the expected output/behavior?
- What are the edge cases?
- What errors should be handled?
Ask clarifying questions if requirements are ambiguous.
## Step 2: Choose Test Type
| Test Type | Use For | Location | Example |
|-----------|---------|----------|---------|
| Model spec | Validations, scopes, instance methods | `spec/models/` | Testing `User#full_name` |
| Request spec | API endpoints, HTTP responses | `spec/requests/` | Testing `POST /api/users` |
| System spec | Full user flows with JavaScript | `spec/system/` | Testing login flow |
| Service spec | Business logic, complex operations | `spec/services/` | Testing `CreateOrderService` |
| Job spec | Background job behavior | `spec/jobs/` | Testing `SendEmailJob` |
## Step 3: Write Failing Spec (RED)
### Spec Structure
```ruby
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ClassName, type: :spec_type do
describe '#method_name' do
subject { described_class.new(args) }
context 'when condition is met' do
let(:dependency) { create(:factory) }
it 'behaves as expected' do
expect(subject.method_name).to eq(expected_value)
end
end
context 'when edge case' do
it 'handles gracefully' do
expect { subject.method_name }.to raise_error(SpecificError)
end
end
end
end
```
### Good Spec Characteristics
- **One behavior per example**: Each `it` block tests one thing
- **Clear description**: Reads like a sentence when combined with `describe`/`context`
- **Minimal setup**: Only create data needed for the specific test
- **Fast execution**: Avoid unnecessary database hits, use `build` over `create` when possible
- **Independent**: Tests don't depend on order or shared state
### Templates
- See [unit_spec.erb](templates/unit_spec.erb) for model/service specs
- See [request_spec.erb](templates/request_spec.erb) for API specs
## Step 4: Verify Failure
Run the spec:
```bash
bundle exec rspec path/to/spec.rb --format documentation
```
The spec MUST fail with a clear message indicating:
- What was expected
- What was received (or that the method/class doesn't exist)
- Why it failed
**Important**: If the spec passes immediately, you're not doing TDD. Either:
- The behavior already exists (check if this is intentional)
- The spec is wrong (not testing what you think)
## Step 5: Implement (GREEN)
Write the MINIMUM code to pass:
- No optimization yet
- No edge case handling (unless that's what you're testing)
- No refactoring
- Just make it work
```ruby
# Start with the simplest thing that could work
def full_name
"#{first_name} #{last_name}"
end
```
## Step 6: Verify Pass
Run the spec again:
```bash
bundle exec rspec path/to/spec.rb --format documentation
```
It MUST pass. If it fails:
1. Read the error carefully
2. Fix the implementation (not the spec, unless the spec was wrong)
3. Run again
## Step 7: Refactor
Now improve the code while keeping tests green:
### Refactoring Targets
- **Extract methods**: Long methods → smaller focused methods
- **Improve naming**: Unclear names → intention-revealing names
- **Remove duplication**: Repeated code → shared abstractions
- **Simplify logic**: Complex conditionals → cleaner patterns
### Refactoring Rules
1. Make ONE change at a time
2. Run specs after EACH change
3. If specs fail, undo and try different approach
4. Stop when code is clean (don't over-engineer)
## Step 8: Final Verification
Run all related specs:
```bash
bundle exec rspec spec/models/user_spec.rb
```
All specs must pass. If any fail:
- Undo recent changes
- Try a different refactoring approach
- Consider if the failing spec reveals a real bug
## Common Patterns
### Testing Validations
```ruby
describe 'validations' do
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to validate_uniqueness_of(:email).case_insensitive }
it { is_expected.to validate_length_of(:name).is_at_most(100) }
end
```
### Testing Associations
```ruby
describe 'associations' do
it { is_expected.to belong_to(:organization) }
it { is_expected.to have_many(:posts).dependent(:destroy) }
end
```
### Testing Scopes
```ruby
describe '.active' do
let!(:active_user) { create(:user, status: :active) }
let!(:inactive_user) { create(:user, status: :inactive) }
it 'returns only active users' do
expect(User.active).to contain_exactly(active_user)
end
end
```
### Testing Service Objects
```ruby
describe '#call' do
subject(:result) { described_class.new.call(params) }
context 'with valid params' do
let(:params) { { email: 'test@example.com' } }
it 'returns success' do
expect(result).to be_success
end
it 'creates a user' do
expect { result }.to change(User, :count).by(1)
end
end
context 'with invalid params' do
let(:params) { { email: '' } }
it 'returns failure' do
expect(result).to be_failure
end
end
end
```
## Anti-Patterns to Avoid
1. **Testing implementation, not behavior**: Test what it does, not how
2. **Too many assertions**: Split into separate examples
3. **Brittle tests**: Don't test exact error messages or timestamps
4. **Slow tests**: Use `build` over `create`, mock external services
5. **Mystery guests**: Make test data explicit, not hidden in factories
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「tdd-cycle」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次