如何存根这个类

时间:2012-10-13 21:25:15

标签: ruby rspec

我有一个名为Board的课程。在其中我初始化网格。

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

我无法弄清楚存根或模拟应该如何看待......

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

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

有人可以帮忙吗?

对于fyi而言,这是实际的班级董事会....感谢您的帮助,我已经盯着这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

1 个答案:

答案 0 :(得分:0)

这是我的想法。这不一定是捣乱。只需从简单的测试开始,您就可以通过存根,模拟或其他方式提供更多功能。

你有一个Board类的对象。此对象具有属性gridinitialize方法等输入内容,并且具有drawgridspace_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