10

我想测试 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 任务中测试另一个私有方法......但我稍后会担心。

4

3 回答 3

8

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

require 'that_new_module'

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

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

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

通过这种方式,您可以测试和重构实现,而无需触及 rake 任务。

于 2012-01-20T12:30:49.683 回答
6

你可以这样做:

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

我自己尝试过……在 Rake 命名空间中定义方法与在顶层定义方法相同。

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

于 2012-01-26T21:19:23.147 回答
1

在已经定义了 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
于 2018-11-09T00:51:37.053 回答