0

I have a completely separate Ruby file that reads from Standard Input and writes to Standard Output.

I have certain test cases that I want to try. How do I pass my inputs to Standard Input to the file, and then test the Standard Output against the expected results?


As an example, here's the stuff I've already figured out:

There's a file that reads a number from standard input, squares it, and writes it to standard input

square.rb:

#!/usr/local/bin/ruby -w

input = STDIN.read

# square it
puts input.to_i ** 2

Complete the pass_input_to_file method of 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 Answers 2

2

You can use the Ruby Open3 Library to submit STDIN when calling a ruby script.

require 'open3'

def pass_input_to_file(input)
  output, _status = Open3.capture2('path_to_script', :stdin_data => input)
  output
end
Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way to test this would probably be to have your program look to see if it was passed any arguments first. Something like this:

#!/usr/local/bin/ruby -w

input = ARGV[0] || STDIN.read

# square it
puts input.to_i ** 2

and then you can shell out to test it:

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

Otherwise, I would reach for something like expect to automate a subshell.


As an aside, for more complicated programs, using OptionParser or a CLI gem is probably better than looking at ARGV directly.

1 Comment

Thank you for your answer Chris! :) Unfortunately, the square.rb file was a stand-in for any kind of file (even non-Ruby) that reads and writes STD IN and OUT, respectively. One that we don't have control over. The backticks to execute shell code idea was something I started using immediately after posting this question, but it's more Bash in Ruby that Ruby itself :). Still a valid way to do it though, and thank you for help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.