简体   繁体   中英

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

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

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, eg 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) 

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

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

for me (rails-6)

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

=> require not necnessary in my case

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM