I would like to test my ruby gem using Minitest. I don't know how to set up the test file to test command line arguments. I know that my command line arguments are going to come from a variable ARGV
, but I don't know how to access that through Minitest.
I also need to know if I have to require the executable in the bin
folder, or the specific ruby file (in this case, a file called CLI.rb
).
This answer is the closest that I've found on Stackoverflow, but the answer seems to be too far removed from what I'm trying to do to be useful, at least as far as I can tell.
Don't bother messing with ARGV
in your tests. It's a constant, and should be treated as such. Instead, decouple the code you need to test so you can just pass whatever data you want to it. The exe should just instantiate the CLI class, and pass ARGV
to it. There's no need to test that file more than just making sure it runs since it's so basic.
Here's what your exe should look like:
require 'mygem'
MyGem::CLI.new(ARGV).run
The CLI code:
module MyGem
class CLI
def initialize(argv)
@options = parse_argv(argv)
end
def run
# main code here
end
private
def parse_argv(argv)
# I'd use getoptlong for this since it's built in to Ruby.
end
end
end
Then your test would look something like this:
require 'test_helper'
module MyGem
class CLITest < MiniTest::Test
def test_help_with_no_args
out, err = capture_io { CLI.new([]).run }
assert_empty err, 'nothing should be written to STDERR'
refute_empty out, 'help should be written to STDOUT'
end
end
end