我無法弄清楚如何編寫一個可以工作的測試,它也不會在CL中的腳本中運行任何東西。當@counter是9時,它應該觸發#tie_game?但它不起作用。 @counter初始化爲0,並且每次玩家在遊戲板上放置一個X或一個O時增加1。我如何測試一次@counter是9,它稱爲tie_game?而當它小於9時,它不會?rspec測試如果方法被調用
def initialize(player1, player2)
@player1 = player1
@player2 = player2
@rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@wins = [1, 2, 3], [4, 5, 6], [7, 8, 9],
[1, 4, 7], [2, 5, 8], [3, 6, 9],
[1, 5, 9], [3, 5, 7]
@selected_numbers = []
@counter = 0
end
def increment_counter
@counter += 1
if @counter == 9
tie_game?
end
end
def tie_game?
puts "The game was a tie. Nicely played #{@player1} & #{@player2}!"
play_again
end
我試過這個:你能解釋它爲什麼不起作用嗎?
describe "increment_counter" do
context "counter equals 9" do
it "calls tie_game?" do
game.instance_variable_set(:@counter, 9)
allow(game).to receive(:increment_counter)
#expect(STDOUT).to receive(:puts).with("The game was a tie. Nicely played #{@player1} & #{@player2}!")
expect(game).to receive(:tie_game?)
end
end
context "counter is less than 9" do
it "does not call tie_game?" do
game.instance_variable_set(:@counter, 4)
game.increment_counter
expect(game).not_to receive(:tie_game?)
end
end
end
我發佈我的答案後,我看到了您的編輯。它沒有爲你工作的原因是你在設定期望之後永遠不會實際調用你的代碼。在測試是否發送和接收消息時,您必須反轉期望/運行順序。 – JasonK
好的真棒。非常感謝您的幫助,這肯定更有意義 –