51
votes

I am building up an integration test suite and there is one bit of logic that I need to have a clean database for. How can I run the db:test:purge task inside of one of my tests?

I am using: ruby 1.9.2, rails 3.0.9, rspec 2.6

5

5 Answers

57
votes

You can invoke Rake tasks as following:

require 'rake'
Rake::Task[name].invoke

In this case this would result in the following code:

require 'rake'
Rake::Task['db:test:purge'].invoke
37
votes

Approved answer didn't work for me, when I needed to execute my own rake task

Here's my solution

Put in the top of the spec file

require 'rake'

Place these lines where you need to execute your custom rake task, e.g. rake update_data from the file example.rake

load File.expand_path("../../../lib/tasks/example.rake", __FILE__)
# make sure you set correct relative path 
Rake::Task.define_task(:environment)
Rake::Task["update_data"].invoke

My environment:

rails (4.0.0)
ruby (2.0.0p195)
rspec-core (2.14.7) 
rspec-expectations (2.14.3) 
rspec-mocks (2.14.4) 
rspec (2.14.1) 
rspec-rails (2.14.0) 
17
votes

If we require to use multiple rake tasks we can add

require "rake"
Rails.application.load_tasks

Then simply call any task.

Rake::Task['sync:process_companies'].invoke

Though I cant confirm if its slower because it loads all the tasks

1
votes

We need to require the task also

require 'rake'
Rake.application.rake_require 'tasks/new_adapter'

After this, just call the task

Rake::Task['new:adapter'].invoke
1
votes

for me (rails-6)

Rails.application.load_tasks
Rake::Task['app:sync'].invoke

=> require not necnessary in my case