8

次のような gets.chomp を使用した単純な関数があります。

def welcome_user
   puts "Welcome! What would you like to do?"
   action = gets.chomp
end 

ruby次のような組み込みTestCaseスイートを使用してテストしたいと思います。

class ViewTest < Test::Unit::TestCase
   def test_welcome
      welcome_user      
   end 
end 

問題は、そのテストを実行するとgets.chomp、ユーザーが何かを入力する必要があるため、テストが停止することです。を使用してユーザー入力をシミュレートする方法はありrubyますか?

4

3 に答える 3

14

パイプを作成し、その「読み取り終了」を に割り当てることができます$stdin。パイプの「書き込み終了」への書き込みは、ユーザー入力をシミュレートします。

with_stdinパイプをセットアップするための小さなヘルパー メソッドの例を次に示します。

require 'test/unit'

class View
  def read_user_input
    gets.chomp
  end
end

class ViewTest < Test::Unit::TestCase
  def test_read_user_input
    with_stdin do |user|
      user.puts "user input"
      assert_equal(View.new.read_user_input, "user input")
    end
  end

  def with_stdin
    stdin = $stdin             # remember $stdin
    $stdin, write = IO.pipe    # create pipe assigning its "read end" to $stdin
    yield write                # pass pipe's "write end" to block
  ensure
    write.close                # close pipe
    $stdin = stdin             # restore $stdin
  end
end
于 2013-06-05T21:27:48.497 に答える