测试与质量
RSpec/RuboCop。
测试与质量
这一课你将能做到
- 用 Minitest 写单元测试,用 RSpec 写行为驱动测试(BDD)
- 用 Pry 和 Byebug 调试 Ruby 代码,设置断点和检查变量
- 用 RuboCop 统一代码风格,用 YARD 写文档注释
为什么要学
Ruby 社区有「测试文化」——不写测试的 Ruby 代码等于没写完。Rails 的 rails test、CI 流水线里的 rspec、代码审查里的 RuboCop 检查,测试和质量工具是 Ruby 开发者的日常。不写测试,代码不敢重构;不用 RuboCop,团队风格不统一。
人话:测试是「安全网」——改代码时不怕摔死;RuboCop 是「交警」——统一交通规则;Pry 是「透视镜」——运行时看代码内部。三者配合,代码从「能跑」变成「可维护」。
先建立图像
Ruby 质量工具链
┌─────────────┬─────────────────────────────────┐
│ 测试框架 │ Minitest(标准库) / RSpec(BDD) │
│ 断言库 │ Minitest::Assertions / RSpec::Matchers │
│ Mock/Stub │ Minitest::Mock / RSpec Mocks │
│ 调试器 │ Pry(交互式) / Byebug(断点) │
│ 代码风格 │ RuboCop / Standard │
│ 文档 │ YARD / RDoc │
│ 覆盖率 │ SimpleCov │
└─────────────┴─────────────────────────────────┘
跟着做
步骤 1:Minitest——标准库测试
# calculator.rb
class Calculator
def add(a, b)
a + b
end
def divide(a, b)
raise ArgumentError, "除数不能为 0" if b.zero?
a / b
end
end
# test_calculator.rb
require "minitest/autorun"
require_relative "calculator"
class TestCalculator < Minitest::Test
def setup
@calc = Calculator.new
end
def test_add
assert_equal 5, @calc.add(2, 3)
end
def test_divide
assert_equal 2, @calc.divide(10, 5)
end
def test_divide_by_zero
assert_raises(ArgumentError) { @calc.divide(10, 0) }
end
def test_add_floats
assert_in_delta 0.3, @calc.add(0.1, 0.2), 0.0001
end
end
# 运行:ruby test_calculator.rb
Minitest 断言速查:
assert_equal expected, actual # 相等
assert_nil obj # 为 nil
assert_includes collection, obj # 包含
assert_raises(Exception) { ... } # 抛异常
assert_in_delta expected, actual, delta # 浮点数近似
refute condition # 断言为假
步骤 2:RSpec——行为驱动测试
# Gemfile
# gem "rspec", "~> 3.12"
# spec/calculator_spec.rb
require_relative "../calculator"
RSpec.describe Calculator do
let(:calc) { Calculator.new } # 懒加载,每个示例独立
describe "#add" do
it "返回两数之和" do
expect(calc.add(2, 3)).to eq(5)
end
it "支持浮点数" do
expect(calc.add(0.1, 0.2)).to be_within(0.0001).of(0.3)
end
end
describe "#divide" do
it "返回商" do
expect(calc.divide(10, 5)).to eq(2)
end
it "除数为 0 时抛出 ArgumentError" do
expect { calc.divide(10, 0) }.to raise_error(ArgumentError, "除数不能为 0")
end
end
end
# 运行:rspec spec/calculator_spec.rb
# 格式化输出:rspec --format doc