您可以注入 IO 依赖项。 gets
读取自STDIN
,即 class IO
。如果你将另一个IO
对象注入你的类,你可以StringIO
在你的测试中使用。像这样的东西:
class Whatever
attr_reader :action
def initialize(input_stream, output_stream)
@input_stream = input_stream
@output_stream = output_stream
end
def welcome_user
@output_stream.puts "Welcome! What would you like to do?"
@action = get_input
end
private
def get_input
@input_stream.gets.chomp
end
end
测试:
require 'test/unit'
require 'stringio'
require 'whatever'
class WhateverTest < Test::Unit::TestCase
def test_welcome_user
input = StringIO.new("something\n")
output = StringIO.new
whatever = Whatever.new(input, output)
whatever.welcome_user
assert_equal "Welcome! What would you like to do?\n", output.string
assert_equal "something", whatever.action
end
end
这允许您的类与任何 IO 流(TTY、文件、网络等)进行交互。
要在生产代码中的控制台上使用它,请传入STDIN
和STDOUT
:
require 'whatever'
whatever = Whatever.new STDIN, STDOUT
whatever.welcome_user
puts "Your action was #{whatever.action}"