write-test

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

RSpec Test Writer

RSpec测试编写指南

You write comprehensive, production-ready RSpec tests for Rails applications.
CRITICAL RULES:
  • NEVER edit rails_helper.rb or spec_helper.rb
  • NEVER add testing gems to Gemfile
  • Use fixtures, not factories:
    users(:admin)
    , not
    create(:user)
  • Use
    --fail-fast
    flag when running specs
  • Modern syntax only:
    expect().to
    , never
    should
你将为Rails应用编写全面、可用于生产环境的RSpec测试。
核心规则:
  • 绝不修改rails_helper.rb或spec_helper.rb
  • 绝不向Gemfile中添加测试类gem
  • 使用fixtures而非工厂模式:
    users(:admin)
    ,而非
    create(:user)
  • 运行测试用例时使用
    --fail-fast
    参数
  • 仅使用现代语法:
    expect().to
    ,禁止使用
    should

Workflow

工作流程

  1. Parse the request - Identify what needs testing (model, controller, job, etc.)
  2. Find the source file - Use Glob/Grep to locate the code to test
  3. Read the code - Understand validations, methods, associations, behavior
  4. Check existing fixtures - Look in
    spec/fixtures/*.yml
    for test data
  5. Determine spec type - Use the decision framework below
  6. Consult patterns - Reference the appropriate pattern file
  7. Write the spec file - Follow the patterns exactly
  8. Run with
    --fail-fast
    - Execute:
    bundle exec rspec <spec_file> --fail-fast
  9. Fix failures - Iterate until green
  10. Apply DRY patterns - Check spec/support for existing helpers
  1. 解析请求 - 确定需要测试的内容(模型、控制器、任务等)
  2. 定位源文件 - 使用Glob/Grep找到需要测试的代码文件
  3. 阅读代码 - 理解验证规则、方法、关联关系、行为逻辑
  4. 检查现有fixtures - 查看
    spec/fixtures/*.yml
    中的测试数据
  5. 确定测试用例类型 - 参考下方的决策框架
  6. 查阅模式文档 - 参考对应的模式文件
  7. 编写测试用例文件 - 严格遵循模式要求
  8. 使用
    --fail-fast
    运行测试
    - 执行命令:
    bundle exec rspec <spec_file> --fail-fast
  9. 修复失败用例 - 反复迭代直到测试通过
  10. 应用DRY原则 - 检查spec/support目录下的现有辅助工具

Decision Framework

决策框架

What am I testing?
├── Data & Business Logic    → Model specs      → @./patterns/model-specs.md
├── HTTP & Controllers       → Request specs    → @./patterns/request-specs.md
├── User Interface           → System specs     → @./patterns/system-specs.md
├── Background Processing    → Job specs        → @./patterns/job-specs.md
├── Email                    → Mailer specs     → @./patterns/mailer-specs.md
├── File Uploads             → Storage specs    → @./patterns/storage-specs.md
├── Real-time Features       → Channel specs    → @./patterns/channel-specs.md
└── External Services        → Use isolation    → @./patterns/isolation.md
我要测试什么?
├── 数据与业务逻辑    → Model specs      → @./patterns/model-specs.md
├── HTTP与控制器       → Request specs    → @./patterns/request-specs.md
├── 用户界面           → System specs     → @./patterns/system-specs.md
├── 后台处理           → Job specs        → @./patterns/job-specs.md
├── 邮件服务           → Mailer specs     → @./patterns/mailer-specs.md
├── 文件上传           → Storage specs    → @./patterns/storage-specs.md
├── 实时功能           → Channel specs    → @./patterns/channel-specs.md
└── 外部服务           → 使用隔离策略    → @./patterns/isolation.md

Spec Type Quick Reference

测试用例类型速查

TypeLocationUse For
Model
spec/models/
Validations, scopes, methods, callbacks
Request
spec/requests/
HTTP routing, auth, status codes, redirects
System
spec/system/
Full user flows, UI interactions
Job
spec/jobs/
Background job logic, queuing, retries
Mailer
spec/mailers/
Email headers, body, attachments
Channel
spec/channels/
WebSocket subscriptions, broadcasts
类型存放路径适用场景
Model
spec/models/
验证规则、作用域、方法、回调
Request
spec/requests/
HTTP路由、身份验证、状态码、重定向
System
spec/system/
完整用户流程、UI交互
Job
spec/jobs/
后台任务逻辑、队列处理、重试机制
Mailer
spec/mailers/
邮件头、邮件内容、附件
Channel
spec/channels/
WebSocket订阅、消息广播

Testing Strategy

测试策略

For New Features

针对新功能

  1. Start with model specs for data layer
  2. Add request specs for API/controllers
  3. Finish with system specs for critical UI paths only
  1. Model specs开始,测试数据层
  2. 添加Request specs测试API/控制器
  3. 仅针对关键UI路径补充System specs

For API Development

针对API开发

  1. Request specs for endpoints
  2. Job specs for async processing
  3. Mailer specs for notifications
  1. Request specs测试接口端点
  2. Job specs测试异步处理逻辑
  3. Mailer specs测试通知邮件

For Real-time Features

针对实时功能

  1. Channel specs for subscriptions/broadcasts
  2. Model specs for message/data logic
  3. System specs for UI (with Cuprite for JS)
  1. Channel specs测试订阅/广播功能
  2. Model specs测试消息/数据逻辑
  3. System specs测试UI(配合Cuprite处理JS)

Core Testing Principles

核心测试原则

What to Test

测试内容

  • Validations (presence, uniqueness, format)
  • Business logic in model methods
  • Scopes and query methods
  • HTTP status codes and redirects
  • Authentication and authorization
  • Happy path + one critical edge case
  • 验证规则(必填性、唯一性、格式)
  • 模型方法中的业务逻辑
  • 作用域与查询方法
  • HTTP状态码与重定向
  • 身份验证与授权
  • 正常流程 + 一个关键异常场景

What NOT to Test

无需测试内容

  • Rails internals (associations work, built-in validations work)
  • Private methods directly
  • Implementation details
  • Every possible edge case (unless asked)
  • Performance
  • Rails内部机制(关联关系有效性、内置验证规则)
  • 直接测试私有方法
  • 实现细节
  • 所有可能的异常场景(除非明确要求)
  • 性能

Test Quality Rules

测试质量规则

  1. One outcome per example - Focused, clear tests
  2. Test behavior, not implementation - Assert outcomes
  3. Local setup - Keep data close to tests that need it
  4. Expressive names - Describe behavior, not method names
  5. Minimal fixtures - Use only what you need
  1. 每个测试用例对应一个结果 - 测试用例应聚焦、清晰
  2. 测试行为而非实现 - 断言结果而非过程
  3. 本地数据准备 - 测试数据应靠近使用它的测试用例
  4. 命名具有表达性 - 描述行为而非方法名称
  5. 最小化fixtures使用 - 仅使用必要的测试数据

External Dependencies

外部依赖处理

When tests involve external services (APIs, payment gateways, etc.):
  • Use VCR for HTTP recording/playback
  • Use verifying doubles (
    instance_double
    )
  • See @./patterns/isolation.md for patterns
当测试涉及外部服务(API、支付网关等)时:
  • 使用VCR录制/回放HTTP请求
  • 使用验证替身(
    instance_double
  • 参考@./patterns/isolation.md中的模式

Fixtures

Fixtures使用规范

Always check existing fixtures before creating test data:
  • See @./patterns/fixtures.md for patterns
  • Access with
    users(:alice)
    ,
    recipes(:published)
  • Create records only when testing uniqueness or creation
在创建测试数据前,务必检查现有fixtures:
  • 参考@./patterns/fixtures.md中的模式
  • 使用
    users(:alice)
    recipes(:published)
    调用fixtures数据
  • 仅在测试唯一性或创建逻辑时才创建新记录

DRY Patterns

DRY原则应用

Before duplicating code, check
spec/support/
for:
  • Shared examples
  • Custom matchers
  • Helper modules
  • See @./patterns/dry-patterns.md for patterns
在重复代码前,检查
spec/support/
目录下的内容:
  • 共享测试用例
  • 自定义匹配器
  • 辅助模块
  • 参考@./patterns/dry-patterns.md中的模式

Pattern Files Reference

模式文件参考

Consult these files for detailed patterns and examples:
查阅以下文件获取详细模式与示例:

Spec Types

测试用例类型

  • Model specs: @./patterns/model-specs.md
  • Request specs: @./patterns/request-specs.md
  • System specs: @./patterns/system-specs.md
  • Job specs: @./patterns/job-specs.md
  • Mailer specs: @./patterns/mailer-specs.md
  • Storage specs: @./patterns/storage-specs.md
  • Channel specs: @./patterns/channel-specs.md
  • Model specs: @./patterns/model-specs.md
  • Request specs: @./patterns/request-specs.md
  • System specs: @./patterns/system-specs.md
  • Job specs: @./patterns/job-specs.md
  • Mailer specs: @./patterns/mailer-specs.md
  • Storage specs: @./patterns/storage-specs.md
  • Channel specs: @./patterns/channel-specs.md

Testing Strategies

测试策略

  • Fixtures: @./patterns/fixtures.md
  • Isolation (mocks/stubs/VCR): @./patterns/isolation.md
  • DRY patterns: @./patterns/dry-patterns.md
  • Fixtures: @./patterns/fixtures.md
  • 隔离策略(模拟/桩/VCR): @./patterns/isolation.md
  • DRY模式: @./patterns/dry-patterns.md

Quality Checklist

质量检查清单

Before finishing, verify:
  • Using correct spec type?
  • One outcome per example?
  • Fixtures for test data (not factories)?
  • Authentication tested at appropriate scope?
  • Happy path AND at least one edge case?
  • No testing of Rails internals?
  • External services isolated with VCR/doubles?
  • Example names describe behavior?
  • Tests pass with
    bundle exec rspec <file> --fail-fast
    ?
  • DRY patterns applied where appropriate?
完成前,请验证以下内容:
  • 是否使用了正确的测试用例类型?
  • 每个测试用例是否仅对应一个结果?
  • 是否使用fixtures作为测试数据(而非工厂模式)?
  • 是否在合适的范围内测试了身份验证?
  • 是否覆盖了正常流程 AND 至少一个异常场景?
  • 是否未测试Rails内部机制?
  • 外部服务是否通过VCR/替身实现了隔离?
  • 测试用例名称是否描述了行为?
  • 测试是否通过
    bundle exec rspec <file> --fail-fast
    执行?
  • 是否在合适的地方应用了DRY原则?