各ケースブランチをテストする必要があります。 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
はい、このコードをすべてのパスをテストするには、各 'ときのためにテストを記述する必要があります'。 – slim
これは実際に考案された例です。ほとんどの場合、一連のイベントが実行されるいくつかの運動事例を作成する必要があります。時にはこれらが非常に複雑になり、簡単にするためにJSONまたはYAMLとして保存された一連のケースファイルで入力と期待される出力を指定する必要があります。可能なすべてのパスを実行するだけでなく、空の文字列、 'nil'値、' $ 'のような無効な入力のような無効なパスの代表的なサンプルも必ず実行してください。 – tadman