SuperAPI AI 工具集

rspec

测试与质量

查看项目

更新于 10-15 21:49

技能介绍

用途:RSpec 是 Ruby(尤其 Rails)的主要测试工具,采用行为驱动开发(BDD)方式,使测试读起来像文档化的规格说明。该技能用于辅助编写 Rails/Ruby 测试。

主要能力:使用 describe、context、it 编写可读、自文档化的规格;测试 ActiveRecord 的校验、scope 与关联(可配合 shoulda-matchers);用 instance_double 与 allow().to receive() 做隔离依赖的 mock 与 stub;通过 FactoryBot 生成灵活的测试记录。

使用方式:在 spec 文件中以 RSpec.describe 定义测试,用嵌套 context 区分前置条件,用 let 做惰性求值绑定,用 expect 断言。示例: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。Rails 项目需在 spec 文件顶部 require 'rails_helper'。

最佳实践:用 instance_double 替代 double 以捕获被改名或删除的方法;单元测试用 build_stubbed 避免访问数据库;每个 it 只保留一个期望;context 以 when 或 with 开头说明前置状态;避免滥用 let! 造成每次测试都提前加载;不要测试框架自身功能,应测试业务逻辑;避免使用含义不明的实例变量,改用显式 let。

常见问题:LoadError: cannot load such file -- rails_helper 表示未加载 helper,需在 spec 顶部 require 'rails_helper';Double received unexpected message 表示测试替身收到未声明的方法调用,需用 allow 或 expect 声明;ExpectationNotMetError 表示期望值或谓词失败,需检查终端 diff 与匹配器语法。

限制:资料未提供安装命令、版本要求、收费与平台信息。