我想测试在 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 任务中测试另一个私有(private)方法......但我可以稍后再担心。
最佳答案
通常的做法是将所有实际代码移动到一个模块中,只留下任务实现:
require 'that_new_module'
namespace :xyz do
task :simple_task => :environment do
ThatNewModule.doit!
end
end
如果您使用环境变量或命令参数,只需将它们传入:
ThatNewModule.doit!(ENV['SOMETHING'], ARGV[1])
通过这种方式,您可以在完全不接触 rake 任务的情况下测试和重构实现。
关于ruby-on-rails - 测试 rake 任务中定义的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8940349/