rails-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Community Ruby on Rails Testing Best Practices

社区版Ruby on Rails测试最佳实践

Comprehensive testing guide for Ruby on Rails applications, maintained by Community. Contains 46 rules across 8 categories, prioritized by impact to guide automated test generation, review, and refactoring.
本指南是针对Ruby on Rails应用的综合性测试指南,由社区维护。包含8个分类下的46条规则,按影响优先级排序,可指导自动化测试生成、评审与重构工作。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new RSpec specs for models, requests, system tests, or jobs
  • Setting up FactoryBot factories with traits and sequences
  • Writing Capybara system tests for user journeys
  • Testing background jobs with Sidekiq or Active Job
  • Reviewing test code for anti-patterns (mystery guests, flaky tests, slow specs)
  • Optimizing test suite performance and CI pipeline speed
  • Organizing test files, shared examples, and custom matchers
在以下场景中可参考本指南:
  • 为模型、请求、系统测试或任务编写新的RSpec测试用例
  • 配置带有trait和sequence的FactoryBot工厂
  • 为用户流程编写Capybara系统测试
  • 使用Sidekiq或Active Job测试后台任务
  • 评审测试代码以发现反模式(神秘依赖、不稳定测试、缓慢测试用例)
  • 优化测试套件性能与CI流水线速度
  • 整理测试文件、共享示例与自定义匹配器

Rule Categories by Priority

按优先级划分的规则分类

PriorityCategoryImpactPrefix
1Test Design & StructureCRITICAL
design-
2Test Data ManagementCRITICAL
data-
3Model TestingHIGH
model-
4Request & Controller TestingHIGH
request-
5System & Acceptance TestingMEDIUM-HIGH
system-
6Async & Background Job TestingMEDIUM
async-
7Test Performance & ReliabilityMEDIUM
perf-
8Test Organization & MaintenanceLOW-MEDIUM
org-
优先级分类影响程度前缀
1测试设计与结构关键
design-
2测试数据管理关键
data-
3模型测试
model-
4请求与控制器测试
request-
5系统与验收测试中高
system-
6异步与后台任务测试
async-
7测试性能与可靠性
perf-
8测试组织与维护中低
org-

Quick Reference

快速参考

1. Test Design & Structure (CRITICAL)

1. 测试设计与结构(关键)

  • design-four-phase-test
    - Use four-phase test structure (setup, exercise, verify, teardown)
  • design-behavior-over-implementation
    - Test observable behavior, not internal implementation
  • design-one-assertion-per-test
    - One logical expectation per test for precise failure diagnosis
  • design-descriptive-test-names
    - Write test names that read like specifications
  • design-avoid-mystery-guest
    - Make all test data visible within the test itself
  • design-avoid-conditional-logic
    - No if/else or loops in test code
  • design-explicit-subject
    - Name subjects explicitly instead of using implicit subject
  • design-four-phase-test
    - 采用四阶段测试结构(准备、执行、验证、清理)
  • design-behavior-over-implementation
    - 测试可观测行为,而非内部实现
  • design-one-assertion-per-test
    - 每个测试仅包含一个逻辑断言,便于精准定位故障
  • design-descriptive-test-names
    - 编写类规格说明的测试名称
  • design-avoid-mystery-guest
    - 确保所有测试数据在测试代码内可见
  • design-avoid-conditional-logic
    - 测试代码中禁止使用if/else或循环
  • design-explicit-subject
    - 显式命名测试主体,避免使用隐式主体

2. Test Data Management (CRITICAL)

2. 测试数据管理(关键)

  • data-factory-traits
    - Use composable factory traits instead of separate factories
  • data-minimal-attributes
    - Specify only attributes relevant to the test
  • data-build-over-create
    - Prefer build/build_stubbed over create when persistence isn't needed
  • data-avoid-fixture-coupling
    - Use factories instead of shared fixtures
  • data-transient-attributes
    - Use transient attributes for complex factory setup
  • data-sequence-unique-values
    - Use sequences for uniqueness-constrained fields
  • data-factory-traits
    - 使用可组合的工厂trait替代独立工厂
  • data-minimal-attributes
    - 仅指定与测试相关的属性
  • data-build-over-create
    - 当不需要持久化时,优先使用build/build_stubbed而非create
  • data-avoid-fixture-coupling
    - 使用工厂而非共享fixture
  • data-transient-attributes
    - 使用临时属性处理复杂的工厂配置
  • data-sequence-unique-values
    - 为有唯一性约束的字段使用sequence

3. Model Testing (HIGH)

3. 模型测试(高)

  • model-test-validations
    - Test validations with boundary cases, not just happy path
  • model-test-associations
    - Test associations explicitly including dependent behavior
  • model-test-scopes
    - Test scopes with matching and non-matching records
  • model-test-callbacks-sparingly
    - Test callback side effects, not callback existence
  • model-test-custom-methods
    - Test public methods with input/output pairs across scenarios
  • model-avoid-testing-framework
    - Don't test ActiveRecord or framework behavior
  • model-test-enums
    - Test enum transitions and generated scopes
  • model-test-validations
    - 测试验证规则时需覆盖边界场景,而非仅测试正常流程
  • model-test-associations
    - 显式测试关联关系,包括依赖行为
  • model-test-scopes
    - 使用匹配与不匹配的记录测试作用域
  • model-test-callbacks-sparingly
    - 测试回调的副作用,而非回调本身是否存在
  • model-test-custom-methods
    - 测试公共方法在不同场景下的输入输出对
  • model-avoid-testing-framework
    - 无需测试ActiveRecord或框架本身的行为
  • model-test-enums
    - 测试枚举值转换与生成的作用域

4. Request & Controller Testing (HIGH)

4. 请求与控制器测试(高)

  • request-over-controller-specs
    - Use request specs over deprecated controller specs
  • request-test-response-status
    - Assert HTTP status codes explicitly
  • request-test-authentication
    - Test authentication boundaries for every protected endpoint
  • request-test-authorization
    - Test authorization for each role
  • request-test-params-validation
    - Test parameter validation and edge cases
  • request-json-response-structure
    - Assert JSON response structure for API endpoints
  • request-over-controller-specs
    - 使用请求测试用例替代已弃用的控制器测试用例
  • request-test-response-status
    - 显式断言HTTP状态码
  • request-test-authentication
    - 为每个受保护的端点测试认证边界
  • request-test-authorization
    - 为每个角色测试授权逻辑
  • request-test-params-validation
    - 测试参数验证与边界场景
  • request-json-response-structure
    - 为API端点断言JSON响应结构

5. System & Acceptance Testing (MEDIUM-HIGH)

5. 系统与验收测试(中高)

  • system-page-objects
    - Encapsulate page interactions in page objects
  • system-use-accessible-selectors
    - Use accessible selectors over CSS/XPath
  • system-avoid-sleep
    - Never use sleep — rely on Capybara's built-in waiting
  • system-test-critical-paths
    - Reserve system tests for critical user journeys
  • system-database-state
    - Use truncation strategy for system test database cleanup
  • system-screenshot-on-failure
    - Capture screenshots on system test failure
  • system-page-objects
    - 将页面交互封装到页面对象中
  • system-use-accessible-selectors
    - 使用可访问选择器替代CSS/XPath
  • system-avoid-sleep
    - 绝不使用sleep,依赖Capybara的内置等待机制
  • system-test-critical-paths
    - 仅为关键用户流程保留系统测试
  • system-database-state
    - 使用截断策略清理系统测试的数据库状态
  • system-screenshot-on-failure
    - 系统测试失败时自动捕获截图

6. Async & Background Job Testing (MEDIUM)

6. 异步与后台任务测试(中)

  • async-separate-enqueue-from-perform
    - Test enqueue and perform separately
  • async-use-fake-mode-default
    - Default to Sidekiq fake mode globally
  • async-test-job-perform
    - Test job perform method directly
  • async-test-mailer-delivery
    - Test mailer delivery with enqueued mail matcher
  • async-test-after-commit
    - Account for transaction-aware job enqueuing in Rails 7.2+
  • async-separate-enqueue-from-perform
    - 分别测试任务入队与执行逻辑
  • async-use-fake-mode-default
    - 全局默认使用Sidekiq fake模式
  • async-test-job-perform
    - 直接测试任务的perform方法
  • async-test-mailer-delivery
    - 使用入队邮件匹配器测试邮件发送
  • async-test-after-commit
    - 在Rails 7.2+版本中需考虑事务感知的任务入队逻辑

7. Test Performance & Reliability (MEDIUM)

7. 测试性能与可靠性(中)

  • perf-parallel-tests
    - Run tests in parallel across CPU cores
  • perf-database-strategy
    - Use transaction strategy for non-system tests
  • perf-profile-slow-specs
    - Profile and fix the slowest specs
  • perf-quarantine-flaky-tests
    - Quarantine flaky tests instead of retrying
  • perf-avoid-before-all-mutation
    - Never mutate state created in before(:all)
  • perf-parallel-tests
    - 跨CPU核心并行运行测试
  • perf-database-strategy
    - 非系统测试使用事务策略
  • perf-profile-slow-specs
    - 分析并修复最慢的测试用例
  • perf-quarantine-flaky-tests
    - 隔离不稳定测试而非重试
  • perf-avoid-before-all-mutation
    - 绝不要修改before(:all)中创建的状态

8. Test Organization & Maintenance (LOW-MEDIUM)

8. 测试组织与维护(中低)

  • org-avoid-deep-nesting
    - Limit context nesting to 3 levels
  • org-shared-examples-sparingly
    - Use shared examples only for true behavioral contracts
  • org-custom-matchers
    - Extract custom matchers for repeated domain assertions
  • org-file-structure-mirrors-app
    - Mirror app directory structure in spec directory
  • org-avoid-deep-nesting
    - 限制上下文嵌套层数不超过3层
  • org-shared-examples-sparingly
    - 仅为真正的行为契约使用共享示例
  • org-custom-matchers
    - 提取自定义匹配器以处理重复的领域断言
  • org-file-structure-mirrors-app
    - 测试目录结构与应用目录结构保持一致

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读单个参考文件以获取详细说明与代码示例:
  • Section definitions - 分类结构与影响程度说明
  • Rule template - 新增规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md分类定义与排序规则
assets/templates/_template.md新规则模板
metadata.json版本与参考信息