Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my rake task running twice in my test?

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/mock'
require 'rake'

class TestScrapeWelcome < ActiveSupport::TestCase
  def setup
    Rake.application.init
    Rake.application.load_rakefile

    @task = Rake::Task['scrape:scrape']
    @task.reenable
  end

  def teardown
    Rake::Task.clear
  end

  test "scraping text and sending to elasticsearch" do
    mocked_client = Minitest::Mock.new
    get_fixtures.each_with_index do |arg,i|
      mocked_client.expect :index, :return_value, [index: "test", type: 'welcome', id: i, body: arg]
    end
    Elasticsearch::Model.stub :client, mocked_client do
      @task.invoke
    end
    assert mocked_client.verify
  end

  private

  def get_fixtures
    (0..11).map { |i|
      File.read("test/fixtures/scrape/index_#{i}.json")
    }
  end

end

But after the task runs once it starts running again without me doing anything (puts prints before and after @task.invoke show that the task is only run the once).

like image 203
Camden Narzt Avatar asked Jul 25 '15 02:07

Camden Narzt


3 Answers

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
like image 188
Camden Narzt Avatar answered Nov 17 '22 23:11

Camden Narzt


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)

like image 42
iheggie Avatar answered Nov 18 '22 00:11

iheggie


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.

like image 1
Jared Avatar answered Nov 18 '22 01:11

Jared