如何缩短这个rspec示例并避免代码重复?

时间:2015-01-23 14:05:35

标签: ruby rspec dry

我正在处理一个旋转了未知位数的数组上的二进制搜索器。这就是我到目前为止所拥有的:

  3 describe RotatedSortedArrayAccessor do                                                                                                                    
  4   context "Array is rotated 0 positions (i.e. not rotated)" do
  5     let(:ary) { [1,3,4,5,7,10,14,15,16,19,20,25] }
  6     it "can find every element present in the array" do
  7       ary.each_with_index do |element, index|
  8         expect(described_class.index_of(ary, element)).to eq(index)
  9       end
 10     end
 11     it "cannot find element not present in the array" do
 12       expect(described_class.index_of(ary, 13)).to eq(nil)
 13     end
 14   end
 15   context "Array is rotated a quarter of the array's length" do
 16     let(:ary) { [19,20,25,1,3,4,5,7,10,14,15,16] }
 17     # TODO:
 18   end
 19   context "Array is rotated half of the array's length" do
 20     let(:ary) { [14,15,16,19,20,25,1,3,4,5,7,10] }
 21     # TODO:
 22   end
 23   context "Array is rotated three quarter of the array's length" do
 24     let(:ary) { [5,7,10,14,15,16,19,20,25,1,3,4] }
 25     # TODO:
 26   end
 27 end         

使用#TODO:评论的部分基本上会重复第6到第13行。如何重新组织此部分以避免代码重复?或者是否适合进行这种重复,因为即使预期大致相似,情境也不同?

1 个答案:

答案 0 :(得分:5)

您可以使用

Rspec shared examples

喜欢这个

RSpec.shared_examples 'rotate_array' do |ary|

  it "can find every element present in the #{ary}" do
    ary.each_with_index do |element, index|
      expect(described_class.index_of(ary, element)).to eq(index)
    end
  end

  it "cannot find element not present in the #{ary}" do
    expect(described_class.index_of(ary, 13)).to eq(nil)
  end
end

describe RotatedSortedArrayAccessor do 
  context "Array is rotated 0 positions (i.e. not rotated)" do
    include_examples 'rotate_array', [1,3,4,5,7,10,14,15,16,19,20,25]
  end

  context "Array is rotated a quarter of the array's length" do
    include_examples 'rotate_array', [19,20,25,1,3,4,5,7,10,14,15,16]
  end

  #TODO...

end

如果您需要了解更多信息。您可以访问此链接http://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

希望这就是你所需要的。