2

ユーザー入力への応答をテストしたいと思います。その入力は、Highlineを使用して照会されます。

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

この質問に似たようなことをして、テストに入れたいと思います。

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

Highlineでこれを行う正しい方法は何ですか?

4

4 に答える 4

10

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

など、彼のコードに示されているように。この情報は、リンクで強調したセットアップに細心の注意を払ってハイライン ソースで見つけることができます。

キーボードでキーを入力する代わりに、彼が STDIN IO パイプを使用する方法に注目してください。

highlineこれが実際に示しているのは、そのようなことをテストするために を使用する必要がないということです。ここでは、彼のテストのセットアップが本当に重要です。StringIOオブジェクトとしての彼の使用とともに 。

于 2013-01-10T08:15:49.700 に答える
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
于 2014-02-03T13:58:11.333 に答える
1

私は HighLine::Test を公開しました - これにより、あるプロセスでテストを実行し、別のプロセスでアプリケーションを実行できます (Selenium を使用したブラウザーベースのテストと同じ方法で)。

于 2013-07-07T14:32:51.717 に答える