Rspec 在 Ruby 中使用枚举器测试方法。方法仅在随后失败时运行

Rspec testing a method using enumerator in Ruby. Method only runs once the fails subsequently

我目前正在 ruby 中完成数独求解器。我使用枚举器创建了一个方法,该方法基于我的 9x9 网格创建 9 个数组,每个数组都引用数独游戏中的 3x3 框。在 Rspec 中对此进行测试时,我发现它仅在一次测试中有效。当我使用相同的方法创建第二个测试时,它总是会失败。当我糊里糊涂时,他们测试他们单独工作,但在第二次测试中调用该方法时却没有。理想情况下,我想将我的方法添加到我的初始化方法中,但是除了一个测试之外,所有测试都失败了。我得到的错误是'StopIteration: 迭代结束'。我明白了,但为什么它不能在每次测试时重新启动?有什么想法吗?

class Grid

BoxOfIndex = [
  0,0,0,1,1,1,2,2,2,0,0,0,1,1,1,2,2,2,0,0,0,1,1,1,2,2,2,
  3,3,3,4,4,4,5,5,5,3,3,3,4,4,4,5,5,5,3,3,3,4,4,4,5,5,5,
  6,6,6,7,7,7,8,8,8,6,6,6,7,7,7,8,8,8,6,6,6,7,7,7,8,8,8
].each

attr_accessor :cells, :rows, :columns, :boxes

def initialize(puzzle)
    @cells = puzzle.split('').map {|v| Cell.new(v) }
    create_boxes
end

def create_rows
    @rows = cells.each_slice(9).to_a
end

def create_columns
    @columns = create_rows.transpose
end

def create_boxes
    @boxes = []
9.times { @boxes << Array.new}
@cells.each{|cell| @boxes[BoxOfIndex.next].concat([cell])}
end

....................Tests below(second test fails)

it "should be able to create boxes with a cell value" do
        grid.create_boxes
        expect(grid.boxes[0][2].value).to eq(5)
    end


    it "should be able to find neighbours of a cell" do
        grid.create_boxes
    end

我认为问题在于您的 BoxOfIndex 常量包含一个迭代器。在您的 create_boxes 方法中,您迭代到最后一个元素。后面的规格不能再调用next,因为你已经到了最后。

更改常量以仅保存数组:

BOX_OF_INDEX = [
  0,0,0,1,1,1,2,2,2,0,0,0,1,1,1,2,2,2,0,0,0,1,1,1,2,2,2,
  3,3,3,4,4,4,5,5,5,3,3,3,4,4,4,5,5,5,3,3,3,4,4,4,5,5,5,
  6,6,6,7,7,7,8,8,8,6,6,6,7,7,7,8,8,8,6,6,6,7,7,7,8,8,8
]

并更改 create_boxes 方法以每次使用新的迭代器:

def create_boxes
  @boxes = []
  iterator = BOX_OF_INDEX.each
  9.times { @boxes << Array.new }
  @cells.each { |cell| @boxes[iterator.next].concat([cell]) }
end