我正在创建一个Rubygem,它将允许我生成jekyll post文件。我开发这个项目的原因之一是学习TDD。这个gem在命令行上具有严格的功能,它必须进行一系列检查,以确保它找到了_posts目录。这取决于两件事:
location选项被传递给
在这一点上,我真的很难测试应用程序的那个部分。所以我有两个问题:
发布于 2011-02-19 20:06:07
我看到的一些项目将它们的命令行工具实现为命令对象(例如:鲁比宝石和我的破线宝石)。这些对象是用ARGV初始化的,只需调用或执行方法,然后启动整个进程。这使这些项目能够将它们的命令行应用程序放到虚拟环境中。例如,它们可以在命令对象的实例变量中保存输入和输出流对象,从而使应用程序独立于使用STDOUT/STDIN。因此,可以测试命令行应用程序的输入/输出。以同样的方式,您可以将当前工作目录保存在实例变量中,从而使命令行应用程序独立于实际工作目录。然后,您可以为每个测试创建一个临时目录,并将此目录设置为Command对象的工作目录。
现在有一些代码:
require 'pathname'
class MyCommand
attr_accessor :input, :output, :error, :working_dir
def initialize(options = {})
@input = options[:input] ? options[:input] : STDIN
@output = options[:output] ? options[:output] : STDOUT
@error = options[:error] ? options[:error] : STDERR
@working_dir = options[:working_dir] ? Pathname.new(options[:working_dir]) : Pathname.pwd
end
# Override the puts method to use the specified output stream
def puts(output = nil)
@output.puts(output)
end
def execute(arguments = ARGV)
# Change to the given working directory
Dir.chdir(working_dir) do
# Analyze the arguments
if arguments[0] == '--readfile'
posts_dir = Pathname.new('posts')
my_file = posts_dir + 'myfile'
puts my_file.read
end
end
end
end
# Start the command without mockups if the ruby script is called directly
if __FILE__ == $PROGRAM_NAME
MyCommand.new.execute
end现在,在测试的设置和解压缩方法中,您可以这样做:
require 'pathname'
require 'tmpdir'
require 'stringio'
def setup
@working_dir = Pathname.new(Dir.mktmpdir('mycommand'))
@output = StringIO.new
@error = StringIO.new
@command = MyCommand.new(:working_dir => @working_dir, :output => @output, :error => @error)
end
def test_some_stuff
@command.execute(['--readfile'])
# ...
end
def teardown
@working_dir.rmtree
end(在这个示例中,我使用了Pathname,它是Ruby标准库和StringIO的一个非常好的面向对象的文件系统API,它对于模拟STDOUT非常有用,因为它是一个IO对象,它流进一个简单的字符串)
在急性试验中,您现在可以使用@working_dir变量来测试文件的存在或内容:
path = @working_dir + 'posts' + 'myfile'
path.exist?
path.file?
path.directory?
path.read == "abc\n"发布于 2011-02-19 19:06:12
根据我的经验(因此这是非常主观的),我认为有时在一些难以测试的领域跳过单元测试是可以的。你需要找出你得到的回报和测试的成本。我的经验法则是,不测试一个类的决定应该是非常不寻常的(大约每300个类不到一个)。
如果您试图测试的内容非常困难,因为与文件系统的依赖关系,我认为您可以尝试提取与文件系统交互的所有位元。
https://stackoverflow.com/questions/5052832
复制相似问题