用途
RSpec 是 Ruby 的测试框架,本技能用于生成 RSpec 风格的测试代码,帮助编写结构清晰、可维护的 Ruby 测试。当用户提到 "RSpec"、"describe do" 等关键词时适用。
主要能力
基础测试结构
使用 RSpec.describe 组织测试,配合 subject 定义被测对象,用 describe '#方法名' 分组,用 it 描述具体行为。示例:
RSpec.describe Calculator do
subject(:calculator) { described_class.new }
describe '#add' do
it 'adds two positive numbers' do
expect(calculator.add(2, 3)).to eq(5)
end
it 'handles negative numbers' do
expect(calculator.add(-1, 1)).to eq(0)
end
end
describe '#divide' do
it 'divides evenly' do
expect(calculator.divide(10, 2)).to eq(5)
end
it 'raises on zero divisor' do
expect { calculator.divide(10, 0) }.to raise_error(ZeroDivisionError)
end
end
end
匹配器(Matchers)
- 相等:
eq(==)、eql(eql?)、equal/be(同一对象) - 比较:
be > 5、be_between(1, 10).inclusive - 真值:
be_truthy、be_falsey、be_nil - 集合:
include、contain_exactly、match_array、include(name: 'Alice') - 字符串:
include、start_with、match(/\d+/) - 类型:
be_a(String)、be_an_instance_of(MyClass) - 异常:
raise_error(StandardError)、raise_error(StandardError, /message/) - 变更:
change(user, :active).from(false).to(true)、change(list, :size).by(1)
钩子与 let
RSpec.describe UserService do
let(:repo) { instance_double(UserRepository) }
let(:service) { described_class.new(repo) }
before(:each) do
allow(repo).to receive(:save).and_return(true)
end
after(:each) { cleanup }
before(:all) { setup_database }
after(:all) { teardown_database }
context 'when creating a user' do
it 'saves to repository' do
service.create('Alice', 'alice@test.com')
expect(repo).to have_received(:save).once
end
end
end
Mock 与 Stub
# Doubles
user = double('User', name: 'Alice', email: 'alice@test.com')
user = instance_double(User, name: 'Alice')
# Stubs
allow(service).to receive(:fetch).and_return(data)
allow(service).to receive(:fetch).with('id').and_return(user)
# Expectations
expect(service).to receive(:save).once
expect(service).to receive(:notify).with('alice@test.com')
expect(service).not_to receive(:delete)
共享示例
RSpec.shared_examples 'a valid model' do
it { is_expected.to be_valid }
it { is_expected.to respond_to(:save) }
end
RSpec.describe User do
subject { described_class.new(name: 'Alice') }
it_behaves_like 'a valid model'
end
使用方式
- 安装:
gem install rspec,然后执行rspec --init - 运行:
bundle exec rspec或rspec spec/models/user_spec.rb - 配置:在
.rspec文件中设置--format documentation --color
反模式对照
| 不推荐 | 推荐 | 原因 |
|---|---|---|
| before 中做重量级准备 | let(惰性求值) | 仅在被使用时才求值 |
| 缺少 context | context 'when...' | 场景更清晰 |
| 实例变量 | let 块 | 更干净、更惰性 |
| should 语法 | expect().to | 现代 RSpec 写法 |
适用场景与限制
适用于 Ruby 项目中使用 RSpec 编写单元测试、集成测试,以及需要 mock/stub 隔离依赖的场景。更深入的模式、调试指南、CI/CD 集成与最佳实践可参考 reference/playbook.md。关于该技能的具体收费、价格、支持平台等信息,资料中暂未提供。