Testing a Rake task that uses OptionParser with RS

2019-07-29 19:09发布

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

The task looks like

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

The task can be executed running rake local:file -- --file=/this/is/a/file.ext

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.

This is my 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

And correctly I get

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

But if I try

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

I get

Don't know how to build task 'process:local_file -- --file=zzzz' (see --tasks)

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?

Thanks

标签: ruby rspec rake
1条回答
地球回转人心会变
2楼-- · 2019-07-29 19:17

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

args = opts.order!(ARGV) {}

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

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()

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

查看更多
登录 后发表回答