RSpec:我如何重构一组重复的测试,唯一改变的是主题和期望

Ner*_*ian 0 refactoring rspec

我有一个测试套件,类似于我用以下代码描述的情况.有两种情境可以定义主题.主题是相似的,相同类型的对象,但具有不同的值.

在那个主题上,我进行了两次测试.两个测试完全相同,另一个测试不同.

建议一个可以消除重复的重构,除了显而易见的"将代码移动到一个方法",我不喜欢它,因为它不清楚.

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
Run Code Online (Sandbox Code Playgroud)

dog*_*unk 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
Run Code Online (Sandbox Code Playgroud)