ruby - 在 Ruby 中为 case 语句编写测试

标签 ruby switch-statement minitest

我正在尝试使用 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/

相关文章:

ruby-on-rails - 用 distance_of_time_in_words 显示剩余时间

java - 从具有给定行/列/表号的数据库样式表中获取数据的最佳方法 - Java

ruby-on-rails - 使用 Minitest 跳过 Pundit 授权

ruby - 使用 Minitest 对 protected 或私有(private)方法进行 stub

ruby - 如何更改默认的 minitest 版本

ruby - 哪种redis数据类型适合存储用户?

ruby - ruby 中的并行 HTTP 请求

ruby-on-rails - Ruby Learning - 知道任何具有中等难度的 Ruby 代码的公共(public) repo 协议(protocol)吗?

android - 在 Android 中实现 switch case 语句的正确方法是什么?

android - 如何使用菜单项中的 switch case 启动不同的 Activity ?