gpt4 book ai didi

ruby - rspec 中的 while 循环

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:43 27 4
gpt4 key购买 nike

我试图了解在 rspec 中测试 while 循环的最佳方法是什么。

我允许用户输入他/她想玩的游戏类型。

def get_action
gets.strip.downcase
end

def type_of_game
puts "Enter the type of game you would like to play (human v. human, computer v. computer, or human v. computer):"
gametype = get_action
until (gametype == "human v. human" || gametype == "computer v. computer" || gametype == "human v. computer")
puts "Please enter a valid game"
gametype = get_action
end
return gametype
end

目前我在 rspec 中有这个,但它会导致无限循环

require "minitest/spec"  
require "minitest/autorun"


describe Game do
before :each do
@game = Game.new
end


it "should prompt to user to enter their gametype again if not human v. human, computer v. computer, or human v. compouter" do
def @game.get_action; "human v. machine" end
expect(@game.type_of_game).to eql("Please enter a valid game")
end

谢谢你的帮助

最佳答案

我会按如下方式重写它,因为它允许我们 stub loop 和 yield(从而避免您遇到的无限循环问题)。这种方法的一个警告是,您将收到游戏类型“人机大战”,因为它会在一次迭代后产生。

class Game
def get_action
gets.strip.downcase
end

def type_of_game
puts 'Enter the type of game you would like to play (human v. human, computer v. computer, or human v. computer):'
gametype = get_action
loop do
break if gametype == 'human v. human' || gametype == 'computer v. computer' || gametype == 'human v. computer'
puts 'Please enter a valid game'
gametype = get_action
end

gametype
end
end

Rspec (3.3.0)

require_relative 'path/to/game'

describe Game do
subject { Game.new }

it 'prompts the user to enter their gametype again if it is incorrect' do
allow(subject).to receive(:gets).and_return('human v. machine')
allow(subject).to receive(:loop).and_yield

expect { subject.type_of_game }
.to output(/Please enter a valid game/)
.to_stdout
end

it 'does not prompt the user to enter their gametype if it is correct' do
allow(subject).to receive(:gets).and_return('human v. human')

expect { subject.type_of_game }
.to_not output(/Please enter a valid game/)
.to_stdout
end

it 'returns the specified gametype if valid' do
allow(subject).to receive(:gets).and_return('human v. human')

expect(subject.type_of_game).to eq('human v. human')
end
end

我使用正则表达式匹配器 (//) 的原因是 stdout 还包括 输入您想要玩的游戏类型(人类对人类,计算机对计算机)计算机,或人与计算机): 我们不关心。

关于ruby - rspec 中的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35543090/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com