单元测试ruby命令行应用程序的代码-如何模拟/通过ARGV [英] unit testing a ruby command line application's code - how to simulate/pass ARGV's
问题描述
我有一个命令行应用程序,它使用thor来处理选项的解析.我想使用test-unit和/或minitest对代码进行单元测试.
I have a command-line application which uses thor to handle the parsing of options. I want to unit test the command-line functionality against the code with test-unit and/or minitest.
我似乎无法弄清楚如何确保ARGV数组(通常会容纳命令行中的选项)容纳我的测试选项,以便可以针对代码进行测试.
I can't seem to figure out how to make sure the ARGV array (which normally would hold the options from the command line) holds my test options so they can be tested against the code.
特定的应用代码:
# 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命令能够正常工作并通过.
I have been able to pass an array into ARGV in the test class, but once I call Myapp/Commands/Build the ARGV appears to be empty. I need to make sure the ARGV array is holding 'build' and 'html' in order for the Build command to work and this to pass.
推荐答案
设置ARGV并避免警告的最简单方法是:
The easiest way to set ARGV and avoid warning is to do:
ARGV.replace your_argv
在 http://apidock.com/ruby/Test/Unit/setup_argv/中找到课
这篇关于单元测试ruby命令行应用程序的代码-如何模拟/通过ARGV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!