rspec

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

RSpec

RSpec

RSpec is the primary testing tool for Ruby (especially Rails). It focuses on "Behavior Driven Development" (BDD), making tests read like documentation specifications.
RSpec是Ruby(尤其是Rails)的主要测试工具。它专注于“行为驱动开发”(BDD),让测试读起来像文档规范一样。

When to Use

适用场景

  • Ruby/Rails Projects: The community standard (over Minitest) for complex apps.
  • Documentation: You want tests that generate readable specs.
  • Ruby/Rails项目:复杂应用的社区标准(优于Minitest)。
  • 文档需求:你希望测试能生成可读性强的规范文档。

Quick Start

快速开始

ruby
undefined
ruby
undefined

user_spec.rb

user_spec.rb

RSpec.describe User, type: :model do context "when newly created" do it "has no name" do user = User.new expect(user.name).to be_nil end end end
undefined
RSpec.describe User, type: :model do context "when newly created" do it "has no name" do user = User.new expect(user.name).to be_nil end end end
undefined

Core Concepts

核心概念

describe
vs
context

describe
vs
context

  • describe
    : Describes the thing being tested (Class, Method).
  • context
    : Describes the condition ("when user is logged in").
  • describe
    :描述被测试的对象(类、方法)。
  • context
    :描述测试的条件(比如“当用户已登录时”)。

Let and Let!

Let 和 Let!

Lazy-loaded variables.
  • let(:user) { User.create }
    : Created only when referenced.
  • let!(:user) { User.create }
    : Created before each test (eager).
延迟加载变量。
  • let(:user) { User.create }
    :仅在被引用时创建。
  • let!(:user) { User.create }
    :在每个测试前创建(立即加载)。

Matchers

匹配器(Matchers)

expect(x).to eq(y)
,
be_valid
,
change { User.count }.by(1)
.
expect(x).to eq(y)
be_valid
change { User.count }.by(1)

Best Practices (2025)

2025年最佳实践

Do:
  • Use
    subject
    : Define the subject of the test explicitly.
  • Keep
    it
    blocks short
    : One expectation per block ideally.
  • Use FactoryBot: Don't use Fixtures (YAML). Use Factories to build test data.
Don't:
  • Don't overuse
    before(:all)
    : It introduces shared state between examples. Use
    before(:each)
    (default).
  • Don't put logic in specs: Specs should verify behavior, not calculate it.
建议
  • 使用
    subject
    :明确定义测试的主题。
  • 保持
    it
    代码块简短
    :理想情况下每个代码块仅包含一个断言。
  • 使用FactoryBot:不要使用Fixtures(YAML),使用工厂模式构建测试数据。
不建议
  • 不要过度使用
    before(:all)
    :它会在测试用例之间引入共享状态。使用
    before(:each)
    (默认)。
  • 不要在测试规范中加入业务逻辑:测试规范应仅验证行为,而非执行计算。

References

参考资料