简体   繁体   English

在Rails环境下使用Rspec测试Rake任务

[英]Testing Rake task with Rspec with Rails environment

I'm trying to test a rake task and it uses an active record in it. 我正在尝试测试rake任务,它在其中使用了活动记录。

require 'spec_helper'
require 'rake'

load File.join(Rails.root, 'lib', 'tasks', 'survey.rake')

describe "survey rake tasks" do
  describe "survey:send_report" do
    it "should send a report" do
      Rake::Task['survey:send_report'].invoke
    end
  end
end

When I run this spec rspec spec/lib/survey_spec.rb , I get this error " 当我运行此规范rspec spec/lib/survey_spec.rb ,出现此错误“

RuntimeError:
   Don't know how to build task 'environment'

How do I load the :enviroment task inside by example spec? 如何通过示例规范在内部加载:enviroment任务?

I think you should first load the tasks: 我认为您应该首先加载任务:

require 'rake'
MyRailsApp::Application.load_tasks

and then invoke your task: 然后调用您的任务:

Rake::Task['survey:send_report'].invoke

I suspect the problem is that your survey:send_report task depends on :environment but you haven't loaded the file that defines the :environment task. 我怀疑问题在于您的survey:send_report任务取决于:environment但是您尚未加载定义:environment任务的文件。 That'll be in rails somewhere, and your main Rakefile loads it. 那会在某个地方,您的主Rakefile会加载它。

So, I think if you change 所以,我想如果你改变

load File.join(Rails.root, 'lib', 'tasks', 'survey.rake')

to

load File.join(Rails.root, 'Rakefile')

it'll work. 会的。

Sounds like your take task may need the Rails environment to be loaded. 听起来您的接听任务可能需要加载Rails环境。 You can stub this out by adding this line to your before(:all) hook: 您可以通过将以下行添加到before(:all)挂钩中来解决这个问题:

Rake::Task.define_task(:environment)

Is your task adding the :enviroment to do it before? 您的任务是否添加了:enviroment来完成? In your .rake file you should have something like this: 在您的.rake文件中,您应该具有以下内容:

namespace :survey do
# ...

task :send_report => :enviroment do
# ... stuff
end

This is because you need to load the full enviroment to do that task. 这是因为您需要加载整个环境才能执行此任务。 You can check this railcast to get more information http://railscasts.com/episodes/66-custom-rake-tasks 您可以检查此铁路广播以获取更多信息http://railscasts.com/episodes/66-custom-rake-tasks

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

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