测试使用 OptionParser 和 RSpec 的 Rake 任务 [英] Testing a Rake task that uses OptionParser with RSpec

查看:37
本文介绍了测试使用 OptionParser 和 RSpec 的 Rake 任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 OptionParser 获取参数的 Rake (12.0) 任务.

I have a Rake (12.0) task that uses OptionParser to get an argument.

任务看起来像

require 'optparse'

namespace :local do
  task :file do
    options = Hash.new

    opts = OptionParser.new
    opts.on('--file FILE') { |file|
      options[:file] = file
    }

    args = opts.order!(ARGV) {}
    opts.parse!(args)

    # Logic goes here.
    # The following is enough for this question
    String.new(options[:file])
  end
end

任务可以运行 rake local:file -- --file=/this/is/a/file.ext

现在我想用 RSpec 验证是否创建了一个新字符串,但我不知道如何在规范中传递文件选项.

Now I want to verify with RSpec that A new string is created but I don't know how to pass the file option inside the spec.

这是我的规格

require 'rake'

RSpec.describe 'local:file' do

  before do
    load File.expand_path("../../../tasks/file.rake", __FILE__)
    Rake::Task.define_task(:environment)
  end

  it "creates a string" do
     expect(String).to receive(:new).with('zzzz')
     Rake.application.invoke_task ("process:local_file")
  end
end

正确地我得到

#<String (class)> received :new with unexpected arguments
         expected: ("zzzz")
              got: (nil)

但是如果我尝试

Rake.application.invoke_task ("process:local_file --file=zzzz")

我明白

不知道如何构建任务'process:local_file -- --file=zzzz'(见--tasks)

我也试过 Rake::Task["process:local_file"].invoke('--file=zzzz') 但仍然 got: (nil).

I have also tried Rake::Task["process:local_file"].invoke('--file=zzzz') but still got: (nil).

我应该如何传递规范中的选项?

How should I pass the option in the spec?

谢谢

推荐答案

假设您从 ARGV(包含传递给脚本的参数的数组)中获取选项:

Given that you take the options from ARGV (the array that contains the arguments passed to the script):

args = opts.order!(ARGV) {}

您可以在调用 Rake::Task 之前将 ARGV 设置为包含您想要的任何选项.

you can set ARGV to contain whatever options you want before invoking Rake::Task.

对我来说(ruby 1.9.3,rails 3.2,rspec 3.4)类似下面的工作

For me (ruby 1.9.3, rails 3.2, rspec 3.4) something like the following works

argv = %W( local:file -- --file=zzzz )
stub_const("ARGV", argv)
expect(String).to receive(:new).with('zzzz')
Rake::Task['local.file'].invoke()

(按照惯例,ARGV[0] 是脚本的名称.)

(By convention, ARGV[0] is the name of the script.)

这篇关于测试使用 OptionParser 和 RSpec 的 Rake 任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆