我有一个命令行应用程序,它使用 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 命令正常工作并通过。
最佳答案
关于ruby - 单元测试 ruby 命令行应用程序的代码 - 如何模拟/传递 ARGV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8621722/