rails-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCommunity 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
按优先级划分的规则分类
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Test Design & Structure | CRITICAL | |
| 2 | Test Data Management | CRITICAL | |
| 3 | Model Testing | HIGH | |
| 4 | Request & Controller Testing | HIGH | |
| 5 | System & Acceptance Testing | MEDIUM-HIGH | |
| 6 | Async & Background Job Testing | MEDIUM | |
| 7 | Test Performance & Reliability | MEDIUM | |
| 8 | Test Organization & Maintenance | LOW-MEDIUM | |
| 优先级 | 分类 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 测试设计与结构 | 关键 | |
| 2 | 测试数据管理 | 关键 | |
| 3 | 模型测试 | 高 | |
| 4 | 请求与控制器测试 | 高 | |
| 5 | 系统与验收测试 | 中高 | |
| 6 | 异步与后台任务测试 | 中 | |
| 7 | 测试性能与可靠性 | 中 | |
| 8 | 测试组织与维护 | 中低 | |
Quick Reference
快速参考
1. Test Design & Structure (CRITICAL)
1. 测试设计与结构(关键)
- - Use four-phase test structure (setup, exercise, verify, teardown)
design-four-phase-test - - Test observable behavior, not internal implementation
design-behavior-over-implementation - - One logical expectation per test for precise failure diagnosis
design-one-assertion-per-test - - Write test names that read like specifications
design-descriptive-test-names - - Make all test data visible within the test itself
design-avoid-mystery-guest - - No if/else or loops in test code
design-avoid-conditional-logic - - Name subjects explicitly instead of using implicit subject
design-explicit-subject
- - 采用四阶段测试结构(准备、执行、验证、清理)
design-four-phase-test - - 测试可观测行为,而非内部实现
design-behavior-over-implementation - - 每个测试仅包含一个逻辑断言,便于精准定位故障
design-one-assertion-per-test - - 编写类规格说明的测试名称
design-descriptive-test-names - - 确保所有测试数据在测试代码内可见
design-avoid-mystery-guest - - 测试代码中禁止使用if/else或循环
design-avoid-conditional-logic - - 显式命名测试主体,避免使用隐式主体
design-explicit-subject
2. Test Data Management (CRITICAL)
2. 测试数据管理(关键)
- - Use composable factory traits instead of separate factories
data-factory-traits - - Specify only attributes relevant to the test
data-minimal-attributes - - Prefer build/build_stubbed over create when persistence isn't needed
data-build-over-create - - Use factories instead of shared fixtures
data-avoid-fixture-coupling - - Use transient attributes for complex factory setup
data-transient-attributes - - Use sequences for uniqueness-constrained fields
data-sequence-unique-values
- - 使用可组合的工厂trait替代独立工厂
data-factory-traits - - 仅指定与测试相关的属性
data-minimal-attributes - - 当不需要持久化时,优先使用build/build_stubbed而非create
data-build-over-create - - 使用工厂而非共享fixture
data-avoid-fixture-coupling - - 使用临时属性处理复杂的工厂配置
data-transient-attributes - - 为有唯一性约束的字段使用sequence
data-sequence-unique-values
3. Model Testing (HIGH)
3. 模型测试(高)
- - Test validations with boundary cases, not just happy path
model-test-validations - - Test associations explicitly including dependent behavior
model-test-associations - - Test scopes with matching and non-matching records
model-test-scopes - - Test callback side effects, not callback existence
model-test-callbacks-sparingly - - Test public methods with input/output pairs across scenarios
model-test-custom-methods - - Don't test ActiveRecord or framework behavior
model-avoid-testing-framework - - Test enum transitions and generated scopes
model-test-enums
- - 测试验证规则时需覆盖边界场景,而非仅测试正常流程
model-test-validations - - 显式测试关联关系,包括依赖行为
model-test-associations - - 使用匹配与不匹配的记录测试作用域
model-test-scopes - - 测试回调的副作用,而非回调本身是否存在
model-test-callbacks-sparingly - - 测试公共方法在不同场景下的输入输出对
model-test-custom-methods - - 无需测试ActiveRecord或框架本身的行为
model-avoid-testing-framework - - 测试枚举值转换与生成的作用域
model-test-enums
4. Request & Controller Testing (HIGH)
4. 请求与控制器测试(高)
- - Use request specs over deprecated controller specs
request-over-controller-specs - - Assert HTTP status codes explicitly
request-test-response-status - - Test authentication boundaries for every protected endpoint
request-test-authentication - - Test authorization for each role
request-test-authorization - - Test parameter validation and edge cases
request-test-params-validation - - Assert JSON response structure for API endpoints
request-json-response-structure
- - 使用请求测试用例替代已弃用的控制器测试用例
request-over-controller-specs - - 显式断言HTTP状态码
request-test-response-status - - 为每个受保护的端点测试认证边界
request-test-authentication - - 为每个角色测试授权逻辑
request-test-authorization - - 测试参数验证与边界场景
request-test-params-validation - - 为API端点断言JSON响应结构
request-json-response-structure
5. System & Acceptance Testing (MEDIUM-HIGH)
5. 系统与验收测试(中高)
- - Encapsulate page interactions in page objects
system-page-objects - - Use accessible selectors over CSS/XPath
system-use-accessible-selectors - - Never use sleep — rely on Capybara's built-in waiting
system-avoid-sleep - - Reserve system tests for critical user journeys
system-test-critical-paths - - Use truncation strategy for system test database cleanup
system-database-state - - Capture screenshots on system test failure
system-screenshot-on-failure
- - 将页面交互封装到页面对象中
system-page-objects - - 使用可访问选择器替代CSS/XPath
system-use-accessible-selectors - - 绝不使用sleep,依赖Capybara的内置等待机制
system-avoid-sleep - - 仅为关键用户流程保留系统测试
system-test-critical-paths - - 使用截断策略清理系统测试的数据库状态
system-database-state - - 系统测试失败时自动捕获截图
system-screenshot-on-failure
6. Async & Background Job Testing (MEDIUM)
6. 异步与后台任务测试(中)
- - Test enqueue and perform separately
async-separate-enqueue-from-perform - - Default to Sidekiq fake mode globally
async-use-fake-mode-default - - Test job perform method directly
async-test-job-perform - - Test mailer delivery with enqueued mail matcher
async-test-mailer-delivery - - Account for transaction-aware job enqueuing in Rails 7.2+
async-test-after-commit
- - 分别测试任务入队与执行逻辑
async-separate-enqueue-from-perform - - 全局默认使用Sidekiq fake模式
async-use-fake-mode-default - - 直接测试任务的perform方法
async-test-job-perform - - 使用入队邮件匹配器测试邮件发送
async-test-mailer-delivery - - 在Rails 7.2+版本中需考虑事务感知的任务入队逻辑
async-test-after-commit
7. Test Performance & Reliability (MEDIUM)
7. 测试性能与可靠性(中)
- - Run tests in parallel across CPU cores
perf-parallel-tests - - Use transaction strategy for non-system tests
perf-database-strategy - - Profile and fix the slowest specs
perf-profile-slow-specs - - Quarantine flaky tests instead of retrying
perf-quarantine-flaky-tests - - Never mutate state created in before(:all)
perf-avoid-before-all-mutation
- - 跨CPU核心并行运行测试
perf-parallel-tests - - 非系统测试使用事务策略
perf-database-strategy - - 分析并修复最慢的测试用例
perf-profile-slow-specs - - 隔离不稳定测试而非重试
perf-quarantine-flaky-tests - - 绝不要修改before(:all)中创建的状态
perf-avoid-before-all-mutation
8. Test Organization & Maintenance (LOW-MEDIUM)
8. 测试组织与维护(中低)
- - Limit context nesting to 3 levels
org-avoid-deep-nesting - - Use shared examples only for true behavioral contracts
org-shared-examples-sparingly - - Extract custom matchers for repeated domain assertions
org-custom-matchers - - Mirror app directory structure in spec directory
org-file-structure-mirrors-app
- - 限制上下文嵌套层数不超过3层
org-avoid-deep-nesting - - 仅为真正的行为契约使用共享示例
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
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 分类定义与排序规则 |
| assets/templates/_template.md | 新规则模板 |
| metadata.json | 版本与参考信息 |