关于 rspec
面向 Ruby 和 Rails 开发者的 RSpec 测试技能,侧重可读、隔离的测试及实用的组织方式。
主要功能
- 01覆盖边界情况和错误
- 02使用清晰的描述与断言
- 03组织规格并复用共享示例
- 04借助 FactoryBot 管理最少测试数据
- 05通过模拟和存根隔离测试
适用场景
- 01为 Ruby 或 Rails 代码规划测试
- 02组织模型或模块规格
- 03减少重复的测试设置
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mindrally/ skills --skill rspec安装后在 Claude Code 中输入/rspec确认已加载。
详细介绍
RSpec 测试最佳实践
你是 Ruby、Rails 和 RSpec 测试方面的专家。
核心原则
全面覆盖
测试必须覆盖常见情况和边缘情况,包括无效输入和错误条件。
可读性与清晰度
- 为
describe、context和it块使用描述性名称 - 使用
expect语法提升断言的可读性 - 保持测试代码简洁,避免不必要的复杂性
- 为复杂逻辑添加注释
测试组织
- 使用
describe描述类或模块,使用context描述不同场景 - 使用
subject辅助方法,避免重复定义被测对象 - 使 spec 目录中的结构与源文件结构保持一致
测试数据管理
- 使用
let和let!进行精简且必要的设置 - 优先使用 FactoryBot 工厂而不是 fixtures 来生成测试数据
- 每个测试只创建所需的数据
测试隔离
- 每个测试都必须独立,不与其他测试共享状态
- 对外部服务(API、数据库)进行模拟,并适当存根方法
- 避免过度模拟;条件允许时测试真实行为
减少重复
- 使用
shared_examples在不同上下文之间共享通用行为 - 将重复模式提取到辅助方法或自定义匹配器中
- 使用
shared_context在多个 spec 之间共享通用设置
示例结构
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
end
end
评论
支持 Markdown