如何用RSpec测试STDIN

时间:2012-08-31 20:37:22

标签: ruby rspec

好的,需要帮助来完成测试。我想测试这个类收到一个字母“O”和 当被调用时,“move_computer”方法返回该人进入cli的WHATEVER。我的心理子处理器告诉我,这是一个简单的赋值变量,用于保存STDIN中的随机人类输入。只是没有把它弄到现在......任何人都指出我正确的方向?

这是我的班级......

class Player
  def move_computer(leter)
    puts "computer move"
    @move = gets.chomp
    return @move
  end
end

我的测试看起来像......

describe "tic tac toe game" do
  context "the player class" do
    it "must have a computer player O" do

      player = Player.new()
      player.stub!(:gets) {"\n"} #FIXME - what should this be?
      STDOUT.should_receive(:puts).with("computer move")
      STDOUT.should_receive(:puts).with("\n") #FIXME - what should this be?
      player.move_computer("O")
    end
  end
end

2 个答案:

答案 0 :(得分:2)

因为move_computer 返回输入,我想你想说:

player.move_computer("O").should == "\n"

我会像这样编写完整的规范:

describe Player do
  describe "#move_computer" do
    it "returns a line from stdin" do
      subject.stub!(:gets) {"penguin banana limousine"}
      STDOUT.should_receive(:puts).with("computer move")
      subject.move_computer("O").should == "penguin banana limousine"
    end
  end
end

答案 1 :(得分:1)

这是我想出的答案......

require_relative '../spec_helper'

# the universe is vast and infinite...it contains a game.... but no players
describe "tic tac toe game" do
  context "the player class" do
    it "must have a human player X"do
      player = Player.new()
      STDOUT.should_receive(:puts).with("human move")
      player.stub(:gets).and_return("")
      player.move_human("X")
    end
    it "must have a computer player O" do
      player = Player.new()
      STDOUT.should_receive(:puts).with("computer move")
      player.stub(:gets).and_return("")
      player.move_computer("O")
    end
  end
end

[给ADMINS注意......如果我只需按一下按钮就能选择所有代码文本和右缩进,那将会很酷。 (嗯......我以为这是过去的特色......?)]