How to call a rake task in rspec

巧了我就是萌 提交于 2019-12-21 08:45:51

问题


I am trying to invoke a rake task in in my rspec.

  require "rake"
  rake = Rake::Application.new
  Rake.application = rake
  rake.init
  rake.load_rakefile
  rake['rake my:task'].invoke

But i am getting error

 Failure/Error: rake['rake db:migrate'].invoke
 RuntimeError:
   Don't know how to build task 'rake db:migrate'

Does anyone have a idea how we can invoke rake task in rspec code.

Any help would be highly appreciated.


回答1:


To pass in the arguments in square brackets to invoke:

rake sim:manual_review_referral_program[3,4]

becomes:

rake['sim:manual_review_referral_program'].invoke(3,4)

If your args are in an array, you can do the following:

args = [3,4]
rake['sim:manual_review_referral_program'].invoke(*args)

More info at this StackOverflow question: How to run Rake tasks from within Rake tasks?.




回答2:


Small namespacing issue, the task is db:migrate not rake db:migrate like the command line usage.

So changing it to this should help:

rake['db:migrate'].invoke



回答3:


A simpler solution for Rails with Rspec :

In your spec_helper (or rails_helper for newer versions of rspec-rails) :

require "rake"
Rails.application.load_tasks

Then when you want to invoke your task you can do the following :

Rake::Task['my:task'].invoke


来源:https://stackoverflow.com/questions/13704976/how-to-call-a-rake-task-in-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!