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

How to shorten this rspec example and avoid code duplication?

我正在一个二进制搜索器上工作,该数组旋转了未知数量的位置。这是我目前所拥有的:

  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行。如何重新组织以避免代码重复?还是因为上下文不同而进行这种重复是否合适,即使期望在很大程度上相似?

你可以使用

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

如果您需要了解更多。你可以访问这个 link http://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

希望这是你需要的。