代码之家  ›  专栏  ›  技术社区  ›  Amin Shah Gilani

如何通过Ruby运行程序并访问其标准输入和输出

  •  0
  • Amin Shah Gilani  · 技术社区  · 6 年前

    我有一些测试用例要尝试。如何将输入传递给文件的标准输入,然后根据预期结果测试标准输出?


    举个例子,我已经弄明白了:

    有一个文件从标准输入中读取一个数字,将其平方,然后将其写入标准输入

    square.rb :

    #!/usr/local/bin/ruby -w
    
    input = STDIN.read
    
    # square it
    puts input.to_i ** 2
    

    pass_input_to_file 方法 test.rb :

    require 'minitest/autorun'
    
    def pass_input_to_file(input)
      # complete code here
    end
    
    class Test < Minitest::Test
      def test_file
        assert_equal pass_input_to_file(2), 4
      end
    end
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Macro    6 年前

    你可以用 Ruby Open3 Library

    require 'open3'
    
    def pass_input_to_file(input)
      output, _status = Open3.capture2('path_to_script', :stdin_data => input)
      output
    end
    
        2
  •  1
  •   Chris Hall    6 年前

    测试这一点最简单的方法可能是让程序先查看是否传递了任何参数。像这样:

    #!/usr/local/bin/ruby -w
    
    input = ARGV[0] || STDIN.read
    
    # square it
    puts input.to_i ** 2
    

    然后你可以测试它:

    def pass_input_to_file(input)
      `path/to/file #{input}`.to_i
    end
    

    expect


    另外,对于更复杂的程序,使用 OptionParser 或者cligem可能比直接查看ARGV更好。