我可以覆盖test_helper.rb中的task:environment来测试rake任务吗? [英] Can I override task :environment in test_helper.rb to test rake tasks?

查看:52
本文介绍了我可以覆盖test_helper.rb中的task:environment来测试rake任务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rakefile中有一系列rake任务,我想作为我的规格等进行测试.每个任务都以以下形式定义:

I have a series of rake tasks in a Rakefile which I'd like to test as part of my specs etc. Each task is defined in the form:

task :do_somthing => :environment do
  # Do something with the database here
end

:environment任务在其中设置ActiveRecord/DataMapper数据库连接和类的位置.我没有将它用作Rails的一部分,但是我有一系列的测试想作为BDD的一部分来运行.

Where the :environment task sets up an ActiveRecord/DataMapper database connection and classes. I'm not using this as part of Rails but I have a series of tests which I like to run as part of BDD.

此代码段说明了我如何尝试测试rake任务.

This snippet illustrates how I'm trying to test the rake tasks.

def setup
  @rake = Rake::Application.new
  Rake.application = @rake
  load File.dirname(__FILE__) + '/../../tasks/do_something.rake'
end

should "import data" do
  @rake["do_something"].invoke
  assert something_in_the_database
end

所以我的帮助请求-是否可以在test_helper.rb文件中重写:environment任务,以便我的rake测试与测试数据库(而不是生产数据库)交互?我尝试在辅助文件中重新定义任务,但这不起作用.

So my request for help - is it possible to over-ride the :environment task in my test_helper.rb file so I my rake testing interacts with the my test database, rather than production? I've tried redefining the task in the helper file, but this doesn't work.

任何解决方案的帮助都将非常有用,因为我在过去的一周中一直坚持这样做.

Any help for a solution would be great, as I've been stuck on this for the past week.

推荐答案

我对类似问题的解决方案"是从我的.rake文件中提取所有逻辑,并创建执行任务的类,只剩下一行调用rake文件,我对不进行过多测试感到很有信心.然后可以正常测试这些类.

My "solution" to a similar problem was to extract all the logic from my .rake files and create classes to perform the tasks, leaving just a one-line call in the rake file, which I felt confident in not testing too hard. The classes could then be tested pretty much normally.

我不知道这对维持一组影响深远的状态的一组复杂的相互依赖的任务的承受能力如何:可能不尽如人意,但这又很可能表明其他设计问题.

I don't know how well this would stand up to a complex set of interdependent tasks that maintain some far-reaching state: probably not well, but then again that would most likely be an indication of some other design problem...

我很好奇我是否错过了更好的东西.

I'm curious to see if I've missed something better.

曾经有一篇博客文章这里(a)说的是相同的东西,而(b)说的更好.看起来他也一样先说了.

There used to be a blog post here that (a) says the same thing and (b) says it better. Looks like he said it first, too.

这篇关于我可以覆盖test_helper.rb中的task:environment来测试rake任务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆