为什么我的rake任务在测试中运行两次? [英] Why is my rake task running twice in my test?

查看:104
本文介绍了为什么我的rake任务在测试中运行两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rake任务测试,该测试是我按照只能在网上找到的唯一示例进行设置的.

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

它看起来像这样:

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

但是任务运行一次后,它又开始运行,而我却没有做任何事情(@task.invoke@task.invoke之前和之后打印,表明该任务仅运行一次).

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).

推荐答案

结果表明,测试运行时已经需要rake并将其初始化,因此需要删除以下所有行,或者将任务定义两次,甚至运行两次如果只调用一次.

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

这篇关于为什么我的rake任务在测试中运行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆