规范测试 Ruby CLI

Spec Testing a Ruby CLI

我正在尝试测试我编写的第一个 ruby CLI(n00b 警报)并需要一些帮助。我的所有代码都在 1 个文件中,其中包括一个 Class、OptionParser 和一些基本的 class 执行方法。这是一个想法

*rb。文件

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])

所以这就是问题所在,我知道我想 运行 一些 rspec 测试 rspec spec/ 我为 class 写的,但是外面的行class 当然得到执行,我留下了 ARGV 错误。

我在找什么

是否有更好的方法来组织我的代码以便我可以测试所有部分,或者我如何编写测试来适应这个文件,我们将不胜感激任何和所有建议。

一个可能的解决方案是用一个条件包装你的选项解析代码,检查文件是直接 运行 还是被其他文件加载。

if __FILE__ == [=10=]
  # option parsing code
end

如果您这样做,那么 if __FILE__ == [=11=] 中的所有代码都不会 运行 您的测试,但其余代码 运行 正常。