我如何测试一个包含 gets.chomp 的函数? [英] How do I test a function with gets.chomp in it?
问题描述
我有一个使用gets.chomp的简单函数,如下所示:
I have a simple function using gets.chomp like this:
def welcome_user
puts "Welcome! What would you like to do?"
action = gets.chomp
end
我想使用 ruby
的内置 TestCase
套件来测试它,如下所示:
I'd like to test it using ruby
's built in TestCase
suite like this:
class ViewTest < Test::Unit::TestCase
def test_welcome
welcome_user
end
end
问题是,当我运行该测试时,gets.chomp
会停止测试,因为它需要用户输入一些内容.有没有办法只使用 ruby
来模拟用户输入?
The problem is, when I run that test, the gets.chomp
stops the test because it needs the user to enter in something. Is there a way I can simulate user inputs using just ruby
?
推荐答案
你先把方法的 2 个关注点分开:
You first separate the 2 concerns of the method:
def get_action
gets.chomp
end
def welcome_user
puts "Welcome to Jamaica and have a nice day!"
action = get_action
return "Required action was #{action}."
end
然后你单独测试第二个.
And then you test the second one separately.
require 'minitest/spec'
require 'minitest/autorun'
describe "Welcoming users" do
before do
def get_action; "test string" end
end
it "should work" do
welcome_user.must_equal "Required action was test string."
end
end
至于第一个,你可以
- 手动测试它并确保它不会损坏(推荐方法,TDD 不是一种信仰).
- 获取有问题的shell的被颠覆版本并使其模仿用户,并进行比较
get_action
是否确实获取了用户输入的内容.
- Test it by hand and rely that it won't break (recommended approach, TDD is not a religion).
- Get the subverted version of the shell in question and make it imitate the user, and compare
whether
get_action
indeed gets what the user types.
虽然这是对您的问题的实用答案,但我不知道该怎么做 2.,我只知道如何模仿浏览器后面的用户 (watir-webdriver
) 而不是后面的外壳会话.
While this is a practical answer to your problem, I do not know how to do 2., I only know how to imitate the user behind the browser (watir-webdriver
) and not behind the shell session.
这篇关于我如何测试一个包含 gets.chomp 的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!