单元测试ruby命令行应用程序的代码 – 如何模拟/传递ARGV

我有一个命令行应用程序,它使用thor来处理选项的解析.我想用test-unit和/或minitest对代码进行命令行功能的单元测试.

我似乎无法弄清楚如何确保ARGV数组(通常会从命令行保存选项)保存我的测试选项,以便可以针对代码测试它们.

具体应用代码:

# myapp/commands/build.rb
require 'thor'

module Myapp
  module Commands

    # Define build commands for MyApp command line
    class Build < Thor::Group
      include Thor::Actions

      build = ARGV.shift
      build = aliases[build] || build

      # Define arguments and options
      argument :type
      class_option :test_framework, :default => :test_unit

      # Define source root of application
      def self.source_root
        File.dirname(__FILE__)
      end

      case build

      # 'build html' generates a html
      when 'html'

        # The resulting html
        puts "<p>HTML</p>"
      end
    end
  end
end

可执行文件

# bin/myapp

测试文件

# tests/test_build_html.rb

require 'test/unit'
require 'myapp/commands/build'


class TestBuildHtml < Test::Unit::TestCase
  include Myapp::Commands

  # HERE'S WHAT I'D LIKE TO DO
  def test_html_is_built

    # THIS SHOULD SIMULATE 'myapp build html' FROM THE COMMAND-LINE
    result = MyApp::Commands::Build.run(ARGV << 'html')
    assert_equal result, "<p>HTML</p>"
  end

end

我已经能够在测试类中将数组传递给ARGV,但是一旦我调用Myapp / Commands / Build,ARGV似乎是空的.我需要确保ARGV数组持有’build’和’html’,以便Build命令工作并通过.

设置ARGV并避免警告的最简单方法是:

ARGV.replace your_argv

发现于http://apidock.com/ruby/Test/Unit/setup_argv/class

相关文章
相关标签/搜索