我正在尝试使用 minitest 为 case 语句编写测试。我需要为每个“何时”编写单独的测试吗?我在下面包含了我的代码。现在它只是放置语句,但最终它会将用户重定向到不同的方法。谢谢!
require 'pry'
require_relative 'messages'
class Game
attr_reader :user_answer
def initialize(user_answer = gets.chomp.downcase)
@user_answer = user_answer
end
def input
case user_answer
when "i"
puts "information"
when "q"
puts "quitter"
when "p"
puts "player play"
end
end
end
最佳答案
This answer会帮助你。尽管如此,我还是会发布一种将其应用于您的情况的方法。正如@phortx 在初始化游戏时所建议的那样,使用相关字符串覆盖默认用户输入。然后通过使用 assert_output
我们可以做类似的事情:
#test_game.rb
require './game.rb' #name and path of your game script
require 'minitest/autorun' #needed to run tests
class GameTest < MiniTest::Test
def setup
@game_i = Game.new("i") #overrides default user-input
@game_q = Game.new("q")
@game_p = Game.new("p")
end
def test_case_i
assert_output(/information\n/) {@game_i.input}
end
def test_case_q
assert_output(/quitter\n/) {@game_q.input}
end
def test_case_p
assert_output(/player play\n/) {@game_p.input}
end
end
运行测试...
$ ruby test_game.rb
#Run options: --seed 55321
## Running:
#...
#Finished in 0.002367s, 1267.6099 runs/s, 2535.2197 assertions/s.
#3 runs, 6 assertions, 0 failures, 0 errors, 0 skips
关于ruby - 在 Ruby 中为 case 语句编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247090/