Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a rake task with RSpec?

I have an Ruby 2.1/Rails 3.2 application which uses the asset pipeline. We are also using a fragile (alpha) gem which causes "rake assets:precompile" to fail at times. I would like to write an rspec test which ensures that this rake task always passes before we commit our code.

I wrote a test in spec/asset_precompile_spec.rb which looks like this:

require 'spec_helper'
require 'rake'

describe 'assets:precompile' do
  before { MyApp::Application.load_tasks }
  it { expect { Rake::Task['assets:precompile'].invoke }.not_to raise_exception }
end

I then ran it on the command line using

rspec spec/lib/assets_precompile_spec.rb

The output I got looked like this:

  1) assets:precompile 
     Failure/Error: it { expect { Rake::Task['assets:precompile'].invoke }.not_to raise_exception }
       expected no Exception, got #<RuntimeError: Command failed with status (1): [/home/railsdev/.rvm/rubies/ruby-2.1.2/bin/...]> with backtrace:
         # ./spec/lib/assets_precompile_spec.rb:7:in `block (3 levels) in <top (required)>'
         # ./spec/lib/assets_precompile_spec.rb:7:in `block (2 levels) in <top (required)>'
     # ./spec/lib/assets_precompile_spec.rb:7:in `block (2 levels) in <top (required)>'

Finished in 0.71247 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/lib/assets_precompile_spec.rb:7 # assets:precompile 

I have looked far & wide, and I can't find any example to run "rake assets:precompile" which actually works in my RSpec environment. I have tried explicitly loading the spec_helper.rb file, I have tried explicitly requiring "factory_girl", but I cannot find anything which works.

Is there a way to make a test run this rake task run in a RSpec test?

like image 273
Jay Godse Avatar asked Jul 15 '14 21:07

Jay Godse


People also ask

How do I test rake tasks?

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.

How do I run an RSpec file?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

What are Rake tasks in Rails?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.


1 Answers

Try Rake::Task['assets:precompile:all'].invoke

instead of Rake::Task['assets:precompile'].invoke

In my case it helped.

like image 177
spr Avatar answered Oct 14 '22 05:10

spr