简体   繁体   English

如何使用RSpec测试rake任务?

[英]How to test a rake task with RSpec?

I have an Ruby 2.1/Rails 3.2 application which uses the asset pipeline. 我有一个使用资产管道的Ruby 2.1 / Rails 3.2应用程序。 We are also using a fragile (alpha) gem which causes "rake assets:precompile" to fail at times. 我们还使用了易碎的(alpha)宝石,该宝石有时会导致“ rake asset:precompile”失败。 I would like to write an rspec test which ensures that this rake task always passes before we commit our code. 我想编写一个rspec测试,以确保该rake任务始终在提交代码之前通过。

I wrote a test in spec/asset_precompile_spec.rb which looks like this: 我在spec / asset_precompile_spec.rb中编写了一个测试,如下所示:

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. 我看了很多遍,找不到任何可以在我的RSpec环境中正常运行的“ rake asset:precompile”示例。 I have tried explicitly loading the spec_helper.rb file, I have tried explicitly requiring "factory_girl", but I cannot find anything which works. 我尝试显式加载spec_helper.rb文件,尝试显式要求“ factory_girl”,但找不到任何有效的方法。

Is there a way to make a test run this rake task run in a RSpec test? 有没有办法让此Rake任务在RSpec测试中运行来进行测试?

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

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

In my case it helped. 就我而言,它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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