rspec
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRSpec
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
undefinedruby
undefineduser_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
undefinedRSpec.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
undefinedCore Concepts
核心概念
describe
vs context
describecontextdescribe
vs context
describecontext- : Describes the thing being tested (Class, Method).
describe - : Describes the condition ("when user is logged in").
context
- :描述被测试的对象(类、方法)。
describe - :描述测试的条件(比如“当用户已登录时”)。
context
Let and Let!
Let 和 Let!
Lazy-loaded variables.
- : Created only when referenced.
let(:user) { User.create } - : Created before each test (eager).
let!(:user) { User.create }
延迟加载变量。
- :仅在被引用时创建。
let(:user) { User.create } - :在每个测试前创建(立即加载)。
let!(:user) { User.create }
Matchers
匹配器(Matchers)
expect(x).to eq(y)be_validchange { User.count }.by(1)expect(x).to eq(y)be_validchange { User.count }.by(1)Best Practices (2025)
2025年最佳实践
Do:
- Use : Define the subject of the test explicitly.
subject - Keep blocks short: One expectation per block ideally.
it - Use FactoryBot: Don't use Fixtures (YAML). Use Factories to build test data.
Don't:
- Don't overuse : It introduces shared state between examples. Use
before(:all)(default).before(:each) - Don't put logic in specs: Specs should verify behavior, not calculate it.
建议:
- 使用:明确定义测试的主题。
subject - 保持代码块简短:理想情况下每个代码块仅包含一个断言。
it - 使用FactoryBot:不要使用Fixtures(YAML),使用工厂模式构建测试数据。
不建议:
- 不要过度使用:它会在测试用例之间引入共享状态。使用
before(:all)(默认)。before(:each) - 不要在测试规范中加入业务逻辑:测试规范应仅验证行为,而非执行计算。