Running Rake Tasks in Rspec Tests

I am creating a set of integration tests, and there is one bit of logic for which I need a clean database. How to run a db:test:purge task inside one of my tests?

I use: ruby ​​1.9.2, rails 3.0.9, rspec 2.6

+46
ruby tdd ruby-on-rails-3 rake rspec
Aug 01 2018-11-11T00:
source share
3 answers

You can invoke Rake tasks as follows:

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

In this case, this will result in the following code:

 require 'rake' Rake::Task['db:test:purge'].invoke 
+50
Aug 01 2018-11-11T00:
source share
β€” -

The approved answer didn't work for me when I needed to complete my own rake task

Here is my solution

Insert the top of the specification file

 require 'rake' 

Put these lines where you need to execute your own rake command, for example. rake update_data strong> from example.rake file

 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) 
+32
Nov 14 '13 at 11:49
source share

If we need to use multiple rake tasks, we can add

 require "rake" Rails.application.load_tasks 

Then just call any task.

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

Although I can’t confirm if it is slower because it loads all tasks

+8
Mar 08 '16 at 5:27
source share



All Articles