Ruby RSpec #
一、基本用法 #
ruby
RSpec.describe Calculator do
describe '#add' do
it 'returns the sum of two numbers' do
calc = Calculator.new
expect(calc.add(2, 3)).to eq(5)
end
end
end
二、匹配器 #
ruby
expect(value).to eq(expected)
expect(value).to be_true
expect(value).to be_false
expect(value).to be_nil
expect(array).to include(item)
expect(string).to match(/pattern/)
expect { code }.to raise_error(ErrorClass)
expect { code }.to change { counter }.by(1)
三、测试组织 #
ruby
RSpec.describe User do
subject { User.new(name) }
let(:name) { "Ruby" }
before do
setup_code
end
after do
cleanup_code
end
describe '#greet' do
it 'returns a greeting' do
expect(subject.greet).to eq("Hello, Ruby")
end
end
end
四、运行测试 #
bash
rspec
rspec spec/user_spec.rb
rspec --format documentation
五、总结 #
本章我们学习了:
- 基本语法:describe、it、expect
- 匹配器:eq、be、include等
- 测试组织:subject、let、before
- 运行测试:rspec命令
Ruby文档创建完成!
最后更新:2026-03-27