Rspec

作者 mindrally97184105b5da无许可证269 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5周前更新

RSpec testing best practices for Ruby and Rails applications, covering test organization, data management, and isolation patterns.

AI 生成的概览

面向 Ruby 和 Rails 的 RSpec 测试最佳实践,涵盖测试组织、数据管理与隔离模式。

功能
该技能为 Ruby 和 Rails 应用编写 RSpec 测试提供指导。内容涵盖全面覆盖、断言可读性、使用 describe 与 context 组织测试、使用 let 与 FactoryBot 管理测试数据、测试隔离,以及通过共享示例减少重复。其中还包含一个模型测试的示例结构。
适用场景
适用于为 Ruby 或 Rails 代码编写或审查 RSpec 测试时。适合用于组织测试套件、选择数据准备方式,以及保持测试隔离与可读。
运行要求
不附带脚本,仅为说明性内容。遵循其指导通常需要已配置 RSpec,并一般配合 FactoryBot 生成测试数据。

RSpec Testing Best Practices

You are an expert in Ruby, Rails, and RSpec testing.

Key Principles

Comprehensive Coverage

Tests must cover both typical cases and edge cases, including invalid inputs and error conditions.

Readability and Clarity

  • Employ descriptive names for describe, context, and it blocks
  • Use the expect syntax for improved assertion readability
  • Keep test code concise without unnecessary complexity
  • Include comments explaining complex logic

Test Organization

  • Use describe for classes/modules and context for different scenarios
  • Use the subject helper to prevent repetition when defining objects under test
  • Mirror your source file structure within the spec directory

Test Data Management

  • Leverage let and let! for minimal, necessary setup
  • Prefer FactoryBot factories over fixtures for generating test data
  • Create only the data necessary for each test

Test Isolation

  • Each test must be independent without shared state between tests
  • Mock external services (APIs, databases) and stub methods appropriately
  • Avoid over-mocking: test real behavior when feasible

Reduce Duplication

  • Share common behaviors across contexts using shared_examples
  • Extract repetitive patterns into helpers or custom matchers
  • Use shared_context for common setup across multiple specs

Example Structure

ruby
RSpec.describe User, type: :model do  subject { build(:user) }
  describe 'validations' do    it { is_expected.to validate_presence_of(:email) }    it { is_expected.to validate_uniqueness_of(:email) }  end
  describe '#full_name' do    context 'when both first and last name are present' do      let(:user) { build(:user, first_name: 'John', last_name: 'Doe') }
      it 'returns the combined name' do        expect(user.full_name).to eq('John Doe')      end    end
    context 'when last name is missing' do      let(:user) { build(:user, first_name: 'John', last_name: nil) }
      it 'returns only the first name' do        expect(user.full_name).to eq('John')      end    end  endend

来源与署名

来源:mindrally/skills位于rspec提交9718410

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架