Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Rake task with Rspec with Rails environment

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?

like image 883
user181677 Avatar asked Oct 02 '12 07:10

user181677


People also ask

How do I test rake tasks?

Whenever you are testing Rake tasks, you need to load the tasks from the Rails application itself. Note that in your tests you should change MyApplication to the name of your application. This line locates the task by it's name and returns a Rake::Task object. Then, we call invoke on it, which executes the task.

How do I run a rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.

What is a rake task?

Rake is a software task management and build automation tool created by Jim Weirich. It allows the user to specify tasks and describe dependencies as well as to group tasks in a namespace. It is similar in to SCons and Make.


3 Answers

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
like image 178
Erdem Gezer Avatar answered Oct 02 '22 10:10

Erdem Gezer


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.

like image 42
Myron Marston Avatar answered Oct 02 '22 11:10

Myron Marston


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)
like image 20
Winston Kotzan Avatar answered Oct 02 '22 11:10

Winston Kotzan