测试rake任务中定义的方法

我想测试rake任务中定义的方法。

耙文件

#lib/tasks/simple_task.rake namespace :xyz do task :simple_task => :environment do begin if task_needs_to_run? puts "Lets run this..." #some code which I don't wish to test ... end end end def task_needs_to_run? # code that needs testing return 2 > 1 end end 

现在,我想测试这个方法, task_needs_to_run? 在测试文件中我该怎么做?

补充说明:我理想的是也希望在rake任务中测试另一个私有方法……但我可以稍后再担心。

你可以这样做:

 require 'rake' load 'simple_task.rake' task_needs_to_run? => true 

我自己尝试过这个…在Rake命名空间中定义一个方法与在顶层定义它是一样的。

load Rakefile不会运行任何任务……它只是定义它们。 因此,在测试脚本中load Rakefile没有任何害处,因此您可以测试相关的方法。

通常的方法是将所有实际代码移动到一个模块中,并将任务实现保留为:

 require 'that_new_module' namespace :xyz do task :simple_task => :environment do ThatNewModule.doit! end end 

如果您使用环境变量或命令参数,只需将它们传递给:

 ThatNewModule.doit!(ENV['SOMETHING'], ARGV[1]) 

这样,您可以在不触及rake任务的情况下测试和重构实现。

在具有rake上下文(类似于此)的项目中工作时已经定义:

 describe 'my_method(my_method_argument)' do include_context 'rake' it 'calls my method' do expect(described_class.send(:my_method, my_method_argument)).to eq(expected_results) end end