3

From command line I invoke the rake task as follows;

rake add -- --num1 1 --num2 2

And the task is defined as follows;

require 'optparse'

task :add do

 options = {}
 OptionParser.new do |opts|
   opts.banner = "Usage: rake add [options]"
   opts.on("-o", "--num1 ARG", Integer) { |x| options[:x] = x }
   opts.on("-t", "--num2 ARG", Integer) { |y| options[:y] = y }
 end.parse!

 puts options[:x].to_i + options[:y].to_i
 exit

end

How can I invoke the task from the test case. Can I use

Rake::Task["add"].invoke

If so, how to pass arguments num1 and num2 ?

rashila
  • 91
  • 4
  • 2
    This is an RSpec question but they same approach should be possible - stubbing ARGV. https://stackoverflow.com/questions/43652071/testing-a-rake-task-that-uses-optionparser-with-rspec – max Mar 01 '18 at 13:36

1 Answers1

0

We can stub the ARGV constant and invoke the rake task. And for stubbing the constant we have to use the gem 'minitest-stub-const' to stub the constant. And the relevant code for the test case is as follows;

args = %W( -- --num1=1 --num2=2)
Object.stub_const(:ARGV, args) do
  Rake::Task["add"].invoke
end
rashila
  • 91
  • 4