我正在研究一个旋转了未知位数的阵列上的二进制搜索器.这是我到目前为止所拥有的:
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
Run Code Online (Sandbox Code Playgroud)
评论的部分#TODO:基本上会重复第6到13行.如何重新组织它以避免代码重复?或者是否适合进行这种重复,因为即使预期大致相似,情境也不同?
小智 5
你可以用
Rspec shared examples
Run Code Online (Sandbox Code Playgroud)
像这样
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
Run Code Online (Sandbox Code Playgroud)
如果您需要了解更多信息.你可以访问此链接http://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples
希望这是你需要的.