你可以注入IO依賴。 gets
讀取STDIN
,這是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}"
Thnaks爲'IO.pipe',你教我的東西在那裏。 –
謝謝,喜歡這種方法! –