简体   繁体   中英

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?

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

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

In my case it helped.

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