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 從公開儲存庫中收錄這些內容。

檢舉或申請下架