简体   繁体   English

传递参数时如何测试rake任务

[英]How to test rake task when arguments are passed

I am testing rake task when arguments are passed, I am trying to run a rake task like this 我正在测试传递参数时的rake任务,我正在尝试像这样运行rake任务

rake do_something_after_n_number_of_days 30

when I run 当我跑步时

let(:task) { Rake::Task['do_something_after_n_number_of_days'] }

task.invoke(30)

I get ARGV[1] as nil but when I run the rake task in the shell it works fine. 我将ARGV [1]设置为nil,但是当我在shell中运行rake任务时,它运行正常。

I have looked in to these answers 1 2 but all of them describe this approach 我已经看过这些答案1 2,但所有这些都描述了这种方法

rake do_something_after_n_number_of_days[30] and I can test that with test.invoke(30) but in some shells I have to escape the brackets like this rake do_something_after_n_number_of_days\\[30\\] rake do_something_after_n_number_of_days[30] ,我可以使用test.invoke(30)进行测试,但是在某些外壳中,我必须像这样使用rake do_something_after_n_number_of_days\\[30\\]

It's common practice in commands to use environment variables for configuration. 在命令中,通常使用环境变量进行配置。 You'll see this used in many different gems. 您将看到它在许多不同的宝石中使用。 For your needs, you could do something like this instead: 为了您的需要,您可以执行以下操作:

task :do_something_after_n_number_of_days do
  raise ArgumentError, 'Invalid DAYS environment setting' if ENV['DAYS'].nil?
  puts ENV['DAYS']
end

Then you can set the ENV in your test, like this: 然后,您可以在测试中设置ENV ,如下所示:

let(:task) { Rake::Task['do_something_after_n_number_of_days'] }

context "when DAYS is set" do 
  before { ENV['DAYS'] = '100' }

  it "does something" do 
    expect { task.invoke }.to output("100").to_stdout
  end
end

context "when DAYS is nil" do 
  before { ENV['DAYS'] = nil }

  it "raises an ArgumentError" do 
    expect { task.invoke }.to raise_error(ArgumentError, /Invalid DAYS/)
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM