rails-testing-rspec

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rails Testing with RSpec

基于RSpec的Rails测试

Build comprehensive test suites using RSpec and FactoryBot. This skill covers spec structure, factories, mocking, and testing best practices.
使用RSpec和FactoryBot构建全面的测试套件。本技能涵盖测试用例结构、工厂、Mocking以及测试最佳实践。

Quick Start

快速开始

Add to Gemfile:
ruby
group :test do
  gem 'rspec-rails'
  gem 'factory_bot_rails'
  gem 'faker'
end
Generate RSpec install:
bash
rails generate rspec:install
Write a test:
ruby
require 'rails_helper'

RSpec.describe User, type: :model do
  describe 'validations' do
    it { is_expected.to validate_presence_of(:email) }
    it { is_expected.to validate_uniqueness_of(:email) }
  end
  
  describe '#full_name' do
    it 'returns concatenated first and last name' do
      user = build(:user, first_name: 'John', last_name: 'Doe')
      expect(user.full_name).to eq('John Doe')
    end
  end
end
Run tests:
bash
rspec                    # All specs
rspec spec/models       # Only model specs
rspec spec/models/user_spec.rb:10  # Specific line
添加到Gemfile:
ruby
group :test do
  gem 'rspec-rails'
  gem 'factory_bot_rails'
  gem 'faker'
end
生成RSpec安装文件:
bash
rails generate rspec:install
编写测试用例:
ruby
require 'rails_helper'

RSpec.describe User, type: :model do
  describe 'validations' do
    it { is_expected.to validate_presence_of(:email) }
    it { is_expected.to validate_uniqueness_of(:email) }
  end
  
  describe '#full_name' do
    it 'returns concatenated first and last name' do
      user = build(:user, first_name: 'John', last_name: 'Doe')
      expect(user.full_name).to eq('John Doe')
    end
  end
end
运行测试:
bash
rspec                    # 所有测试用例
rspec spec/models       # 仅模型测试用例
rspec spec/models/user_spec.rb:10  # 特定行

Core Topics

核心主题

RSpec Setup: See rspec-setup.md for configuration, describe blocks, contexts, and common matchers.
Factories: See factories-fixtures.md for FactoryBot setup, defining factories, and sequences.
Mocking: See mocking-stubbing.md for stubbing, mocking, spies, and testing external dependencies.
Patterns: See patterns.md for test organization, DRY specs, and common patterns.
RSpec配置:查看 rspec-setup.md 了解配置、describe块、上下文和常用匹配器。
工厂:查看 factories-fixtures.md 了解FactoryBot配置、定义工厂和序列。
Mocking:查看 mocking-stubbing.md 了解桩(Stub)、Mock、间谍(Spy)以及测试外部依赖。
模式:查看 patterns.md 了解测试组织、DRY测试用例以及常见模式。

Examples

示例

See examples.md for:
  • Model specs with validations and scopes
  • Controller/request specs
  • Integration tests
  • Testing background jobs
查看 examples.md 获取:
  • 带验证和作用域的模型测试用例
  • 控制器/请求测试用例
  • 集成测试
  • 测试后台任务