在Ruby中为case语句编写测试

时间:2016-12-20 16:35:25

标签: 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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

您必须测试每个案例分支。通过RSpec,它将以这种方式工作:

describe Game do
  subject { Game }

  describe '#input' do
     expect_any_instance_of(Game).to receive(:puts).with('information')
     Game.new('i').input

     expect_any_instance_of(Game).to receive(:puts).with('quitter')
     Game.new('q').input

     expect_any_instance_of(Game).to receive(:puts).with('player play')
     Game.new('p').input
    end
end

但是由于puts难以测试,你应该将代码重构为类似的东西:

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"
     "information"
    when "q"
      "quitter"
    when "p"
      "player play"
    end
  end

  def print_input
    puts input
  end
end

然后您可以通过以下方式使用RSpec进行测试:

describe Game do
  subject { Game }

  describe '#print_input' do
    expect_any_instance_of(Game).to receive(:puts).with('quitter')
    Game.new('q').print_input
  end

  describe '#input' do
     expect(Game.new('i').input).to eq('information')
     expect(Game.new('q').input).to eq('quitter')
     expect(Game.new('i').input).to eq('player play')
     expect(Game.new('x').input).to eq(nil)
  end
end