我有一个使用 gets.chomp 的简单函数,如下所示:
def welcome_user
puts "Welcome! What would you like to do?"
action = gets.chomp
end
我想用它来测试它ruby
是内置的TestCase
像这样的套房:
class ViewTest < Test::Unit::TestCase
def test_welcome
welcome_user
end
end
问题是,当我运行该测试时,gets.chomp
停止测试,因为它需要用户输入一些内容。有没有一种方法可以仅使用来模拟用户输入ruby
?
你可以创建一个pipe http://www.ruby-doc.org/core-2.0/IO.html#method-c-pipe并将其“读端”分配给$stdin
。然后写入管道的“写入端”模拟用户输入。
这是一个带有小辅助方法的示例with_stdin
用于设置管道:
require 'test/unit'
class View
def read_user_input
gets.chomp
end
end
class ViewTest < Test::Unit::TestCase
def test_read_user_input
with_stdin do |user|
user.puts "user input"
assert_equal(View.new.read_user_input, "user input")
end
end
def with_stdin
stdin = $stdin # remember $stdin
$stdin, write = IO.pipe # create pipe assigning its "read end" to $stdin
yield write # pass pipe's "write end" to block
ensure
write.close # close pipe
$stdin = stdin # restore $stdin
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)