xentek
xentek

Reputation: 2645

Running Rake tasks in Rspec Tests

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

Upvotes: 59

Views: 29006

Answers (6)

ethaning
ethaning

Reputation: 446

Many of the above answers worked for me for running a single spec. However, I had to take an extra step when running multiple specs for a single rake task.

After each spec, I had to run Rake::Task.clear, as (for some reason) the task would not be run again if it was registered as being already_invoked (i.e. if Rake::Task['my_task'].already_invoked returned true.

I added the following line to my rake task spec:

after { Rake::Task.clear }

and everything worked as expected when running multiple tests for the same rake task.

Upvotes: 7

chmich
chmich

Reputation: 1176

for me (rails-6)

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

=> require not necnessary in my case

Upvotes: 5

Prakriti Gupta
Prakriti Gupta

Reputation: 31

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

Upvotes: 3

coderVishal
coderVishal

Reputation: 9109

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

Upvotes: 19

Sergiy Seletskyy
Sergiy Seletskyy

Reputation: 17190

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) 

Upvotes: 38

user290102
user290102

Reputation:

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

Upvotes: 62

Related Questions