2013-01-10 149 views
1

我想测试对用户输入的响应。该输入查询使用Highline如何使用Highline测试rspec用户输入和输出?

def get_name 
    return HighLine.new.ask("What is your name?") 
end 

我想要做类似的东西this question,并把它在我的测试:

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

什么是海莱做到这一点的正确方法是什么?

回答

8

了解如何测试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 

等等,如他的代码所示。您可以在highline source中找到此信息,密切关注我在链接中突出显示的设置。

注意他是如何使用STDIN IO管道来操作键盘上键盘的。

这是什么表示,真的,你不需要使用highline来测试这种事情。他的测试中的设置在这里非常重要。随着他使用StringIO作为对象。

1

Highline已经有自己的测试,以确保它输出到STDOUT并从STDIN读取。没有理由写这些类型的测试。这与你不写ActiveRecord测试确保属性可以保存并从数据库中读取的原因是一样的。

但是...... 它会如果有对Highline的一个框架,以类似的方式为水豚适用于web表单... 的东西,实际上是从用户界面驱动输入和测试的逻辑是非常有用你的命令行工具。

例如,下面的那种假设测试将是不错:

run 'my_utility.rb' 
highline.should :show_menu 
select :add 
highline.should(:ask).with_prompt("name?") 
enter "John Doe" 
output.should == "created new user" 
1

我已经发表的Highline ::测试 - 它可以让你在运行一个程序的测试,并在其他应用程序(在与使用Selenium进行基于浏览器的测试一样)。

1

我从事这个DSL来尝试解决这个问题:

https://github.com/bonzofenix/cancun

require 'spec_helper' 

describe Foo do 
    include Cancun::Highline 
    before { init_highline_test } 

    describe '#hello' do 
    it 'says hello correctly' do 
    execute do 
     Foo.new.salute 
    end.and_type 'bonzo' 
    expect(output).to include('Hi bonzo') 
    end