如何用RSpec测试STDIN

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

这是我的class级……

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 

因为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 

这是我想出的答案……

 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注意……如果我只需按一下按钮就可以选择所有代码文本和右缩进,那将会很酷。 (嗯……我以为这是过去的特色……?)]