2013-01-10 72 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