Testing Rake task with Rspec with Rails environment

删除回忆录丶 提交于 2019-12-20 17:28:52

问题


I'm trying to test a rake task and it uses an active record in it.

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 "

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

How do I load the :enviroment task inside by example spec?


回答1:


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



回答2:


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. That'll be in rails somewhere, and your main Rakefile loads it.

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.




回答3:


Sounds like your take task may need the Rails environment to be loaded. You can stub this out by adding this line to your before(:all) hook:

Rake::Task.define_task(:environment)



回答4:


Is your task adding the :enviroment to do it before? In your .rake file you should have something like this:

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



来源:https://stackoverflow.com/questions/12686282/testing-rake-task-with-rspec-with-rails-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!