1

我有一门课叫板。在其中我初始化了一个网格。

我想为 rspec 规范的板创建一个模拟或存根(不确定哪个)。

我无法弄清楚存根或模拟应该是什么样子......

stub_board = stub('board') 
stub_board.stub(:[]).with(:b2).and_return("O")

我不知道......为了我想写的测试,我想在板上有一些 O。

有人可以帮忙吗?

仅供参考,这里是实际的班级委员会....感谢您的帮助,我已经盯着这个看了 3 天。

class Board
attr_reader :grid

def initialize(cell_value = " ")
  @grid = {
    a1: cell_value, a2: cell_value, a3: cell_value,
    b1: cell_value, b2: cell_value, b3: cell_value,
    c1: cell_value, c2: cell_value, c3: cell_value
  }
end

def drawgrid
  board = "\n"
  board << "a #{@grid[:a1]}|#{@grid[:a2]}|#{@grid[:a3]} \n"
  board << "----------\n"
  board << "b #{@grid[:b1]}|#{@grid[:b2]}|#{@grid[:b3]} \n"
  board << "----------\n"
  board << "c #{@grid[:c1]}|#{@grid[:c2]}|#{@grid[:c3]} \n"
  board << "----------\n"
  board << "  1 2 3\n"
end

def space_taken?(cell_location)
  @grid[cell_location] != " "
end
end
4

1 回答 1

0

这是我的想法。这不必是 stubing 或 mocking。只需从简单的测试开始,就可以通过 stubing、mocking 或其他方式提供更多功能。

你有一个 Board 类的对象。该对象具有属性gridinitialize方法之类的输入内容,并且具有和之类的输出drawgrid内容space_taken?。因此,测试的想法是设置输入内容并明确具体的输出内容。有可能:

describe Board do

  describe "drawgrid" do

    it "shuold generate default string" do
      board = Board.new
      board.drawgrid.should == "here's your string"
    end

    it "should generate string with cell_value '*'" do
      board = Board.new('*')
      board.drawgrid.should == "string with '*' cell value"
    end

    # and so on
  end

  describe "space_taken?" do

    it "should set cell value" do
      board = Board.new
      board.space_taken?(:a1).should be_false
      board.grid[:a1] = '!'
      board.space_taken?(:a1).should be_true
    end

    # and so on
  end
end

您可以使用代码覆盖率分析工具来帮助您找到未覆盖的行,例如SimpleCov

于 2012-10-13T21:54:35.803 回答