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?
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.
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.
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.
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. 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With