尝试在Rspec中测试我的循环,但是不确定尝试它的最佳方法。尝试了几种不同的选项,但是当我测试输出问题和答案时,似乎都失败了。输出给了我整个循环运行的结果,而答案给了我平局的回报,而不仅仅是gets.chomp答案。
我正在尝试设计一个Tic Tac Toe游戏,并使用循环方法在班上进行游戏。但是,当涉及到在TDD中进行测试时,它会不断显示错误消息。我的代码如下:
def initialize
@player1 = []
@player2 = []
end
def play
i = 0
loop do
i += 1
print "Player 1 play: "
answer = gets.chomp
@player1.push(answer)
if WINNING_RESULTS.include?(@player1[0..2].sort)
return "Player 1 Wins"
break
end
if i == 9
return "It's a Draw"
end
i += 1
print "Player 2 play: "
answer1 = gets.chomp
@player2.push(answer1)
if WINNING_RESULTS.include?(@player2[0..2].sort)
return "Player 2 Wins"
break
end
end
end
我希望结果如下:
it "asks player one to pick a move" do
allow_any_instance_of(Game).to receive(:gets).and_return("TL")
expect { subject.play }.to output("Player 1 play: ").to_stdout
end
上面的那个打印出“ Player 1播放:”“ Player 2:播放”的整个循环,直到我达到9。
it "should receive an answer from the user" do
allow_any_instance_of(Game).to receive(:gets).and_return("TL")
expect(subject.play).to eq("TL")
end
上面的内容是:预期的“ TL”实际为“抽奖”