Why is my rake task running twice in my test?

后端 未结 4 1560
悲&欢浪女
悲&欢浪女 2021-01-12 17:23

I have a rake task test that I setup following the only examples I could find online.

It looks like this:

require \'test_helper\'
require \'minitest/         


        
相关标签:
4条回答
  • 2021-01-12 17:38

    Updated answer for rails 5.1 (using minitest):

    I found I needed the following to load tasks once and only once:

    MyAppName::Application.load_tasks if Rake::Task.tasks.empty?
    

    Alternatively add MyAppName::Application.load_tasks to your test_helper, if you don't mind tasks being loaded even when running individual tests that don't need them.

    (Replace MyAppName with your application name)

    0 讨论(0)
  • 2021-01-12 17:56

    A solution that works for testing the tasks of a Gem that has been made a Railtie so it can add tasks to the Rails app:

    Don't define the Railtie in test mode when you're also defining a Rails::Application class in spec_helper.rb (which allows your tests to call Rails.application.load_tasks). Otherwise the Rake file will be loaded once as a Railtie and once as an Engine:

    class Railtie < Rails::Railtie
      rake_tasks do
        load 'tasks/mygem.rake'
      end
    end unless Rails.env.test? # Without this condition tasks under test are run twice
    

    Another solution would be to put a condition in the Rake file to skip the task definitions if the file has already been loaded.

    0 讨论(0)
  • 2021-01-12 17:56

    I've tried @iheggie answer but it worked in a way that indeed tests were run once but any other task was breaking with Don't know how to build task '<task_name_like_db_migrate>'.

    I'm on Rails 3.2 still. It turned out that there were couple tasks loaded beforehand so the Rake::Task.tasks.empty? was never true and all other useful tasks were not loaded. I've fiddled with it and this version of it works for me right now:

    Rake::Task.clear if Rails.env.test?
    MyAppName::Application.load_tasks
    

    Hope this helps anyone.

    0 讨论(0)
  • 2021-01-12 18:02

    Turns out that rake is already required and initialized when the test runs so all of the following lines need to be removed or the task gets defined twice and runs twice even if you only invoke it once.

    require 'minitest/mock'
    require 'rake'
    ...
    Rake.application.init
    Rake.application.load_rakefile
    
    0 讨论(0)
提交回复
热议问题