我有一个测试套件,类似于我用以下代码描述的情况。有两种情境可以定义主题。主题是相似的,相同类型的对象,但具有不同的值。
在这个主题上,我进行了两次测试。两个测试完全相同,另一个测试不同。
建议一个可以消除重复的重构,除了显而易见的“将代码移动到一个方法”,我不喜欢它,因为它不清楚。
require 'rspec'
describe "tests over numbers" do
context 'big numbers' do
subject { 5000 }
describe "#to_string" do
its(:to_s) {should be_a(String)}
end
describe "#+1" do
it "+1" do
sum = subject+1
sum.should == 5001
end
end
end
context 'small numbers' do
subject { 100 }
describe "#to_string" do
its(:to_s) {should be_a(String)}
end
describe "#+1" do
it "+1" do
sum = subject+1
sum.should == 101
end
end
end
end
答案 0 :(得分:8)
也许共享的例子是要走的路?
shared_example "numbers" do
describe "#to_string" do
it "should convert to a string" do
example.to_s.should be_a(String)
end
end
describe "#+1" do
it "should increment" do
sum = example+1
sum.should == example.next
end
end
end
describe "big_numbers" do
it_behaves_like "numbers" do
let(:example) { 5000 }
end
end
describe "small_numbers" do
it_behaves_like "numbers" do
let(:example) { 100 }
end
end
答案 1 :(得分:1)
[5000, 100].each do |my_test|
subject { my_test }
describe "#to_string" do
its(:to_s) {should be_a(String)}
end
describe "#+1" do
it "+1" do
sum = subject+1
sum.should == my_test + 1
end
end
end