如何使用Highline测试rspec用户输入和输出?

Ove*_*esh 2 ruby io rspec highline

我想测试对用户输入的响应.使用Highline查询该输入:

def get_name
  return HighLine.new.ask("What is your name?")
end
Run Code Online (Sandbox Code Playgroud)

我想做一些类似于这个问题的事情,并把它放在我的测试中:

STDOUT.should_receive(:puts).with("What is your name?")
STDIN.should_receive(:read).and_return("Inigo Montoya")
MyClass.new.get_name.should == "Inigo Montoya"
Run Code Online (Sandbox Code Playgroud)

使用Highline的正确方法是什么?

vgo*_*off 9

了解如何测试Highline的最佳方法是查看作者如何测试他的包.

class TestHighLine < Test::Unit::TestCase
  def setup
    @input    = StringIO.new
    @output   = StringIO.new
    @terminal = HighLine.new(@input, @output)..
  end
..
  def test_agree
    @input << "y\nyes\nYES\nHell no!\nNo\n"
    @input.rewind

    assert_equal(true, @terminal.agree("Yes or no?  "))
    assert_equal(true, @terminal.agree("Yes or no?  "))
    assert_equal(true, @terminal.agree("Yes or no?  "))
    assert_equal(false, @terminal.agree("Yes or no?  "))
....
    @input.truncate(@input.rewind)
    @input << "yellow"
    @input.rewind

    assert_equal(true, @terminal.agree("Yes or no?  ", :getc))
  end


   def test_ask
     name = "James Edward Gray II"
     @input << name << "\n"
     @input.rewind

     assert_equal(name, @terminal.ask("What is your name?  "))
 ....
     assert_raise(EOFError) { @terminal.ask("Any input left?  ") }
   end
Run Code Online (Sandbox Code Playgroud)

等,如他的代码所示.您可以在高线来源中找到这些信息,密切关注我在链接中突出显示的设置.

请注意他如何使用STDIN IO管道在键盘上键入键盘的位置.

这表明,实际上,你不需要highline用来测试那种东西.他的测试中的设置非常关键.随着他使用StringIO作为对象.