Jaison Brooks
Jaison Brooks

Reputation: 5826

Spec Testing a Ruby CLI

I am trying to test the first ruby CLI i've written (n00b alert) and need some help. All my code is within 1 file, this includes a Class, OptionParser and some basic class execution methods. Here's an idea of what that looks like

The *rb. file

require 'optparse'
require 'fileutils'

class Foo
   attr_accessor :arg, :opt

   def initialize(p={})
     @opt = p[:opt] || false
   end
   def do_something(arg)
      @arg = arg
   end
   #more methods...
end

# Options
@options={}
@opt_parser = OptionParser.new do |opt|
    opt.banner = "<{ FooBar }>"
    opt.separator "------------"
    opt.on("-o", "--opt", "An Option" do 
      @options[:opt] = true
    end
end
@opt_parser.parse!

#CLI Execution
@foo = Foo.new(@options)
@foo.do_something(ARGV[0])

So here is the problem, i know would like to run some rspec tests rspec spec/ that i've wrote for the class, however the lines outside the class get executed of course and im left with an ARGV error.

What im looking for

Is there a better way to organize my code so i can test all the pieces, or how could i write a test to accommodate this file, Any and all suggestions would be greatly appreciated.

Upvotes: 0

Views: 129

Answers (1)

Jesus Castello
Jesus Castello

Reputation: 1113

One posible solution is to wrap your option parsing code with a conditional that checks if the file is being run directly or loaded by some other file.

if __FILE__ == $0
  # option parsing code
end

If you do that then all the code inside the if __FILE__ == $0 will not run with your test, but the rest of the code will run normally.

Upvotes: 1

Related Questions