【问题标题】:Rspec- Testing a rake task that calls "abort"Rspec-测试调用“中止”的 rake 任务
【发布时间】:2019-08-16 21:56:11
【问题描述】:

我有一个 rake 任务,如果满足条件,它会调用 abort,这是一个简化的示例:

name :foo do
  desc 'Runs on mondays'
  task bar: :environment do
    abort unless Date.current.monday?
    # do some special stuff
  end
end

当我为这个 rake 任务编写 RSpec 测试时,对于代码中止的测试用例,它会导致其余测试不运行。

我的问题是:在测试中是否有可能以某种方式“存根”中止,以便它继续运行其他测试,或者我别无选择,只能使用另一种方法退出 rake 任务(例如next) 并完全删除 abort

编辑

这是我正在使用的测试的伪代码示例。在我的真实测试文件中,我有其他测试,一旦运行该测试,它就会中止并且不运行其他测试。

require 'rails_helper'
require 'rake'

RSpec.describe 'FooBar', type: :request do
  before { Rake.application.rake_require "tasks/foo" }

  it "doesn't foo the bar on Mondays" do
    allow(Date.current).to receive(:monday?).and_return(true)
    Rake::Task['foo:bar'].execute
    # expect it not to do the stuff
  end
end

最后,我只是将其更改为 next 而不是 abort,但我在 SO 或谷歌搜索中找不到这个问题的答案,所以我想我会问。

【问题讨论】:

  • 你能添加你的测试的一部分,主要是你调用你的任务的地方吗?你会在每个之前调用一次吗?
  • @morissetcl 添加了一个示例,但我不确定它对回答问题有多大帮助。根据我对测试 rake 任务所做的一些研究,我尝试了许多不同的调用,它们都有相同的问题(现在回想起来似乎很明显)。但是我仍然很好奇我是否可以避免它中止测试套件,或者我是否必须始终避免在我想要测试的 rake 任务中中止。

标签: rspec rake


【解决方案1】:

我知道这是一个旧的,但我一直在研究这个,我认为解决这个问题的最好方法是使用raise_error。在您的示例中,这看起来像:

require 'rails_helper'
require 'rake'

RSpec.describe 'FooBar', type: :request do
  before { Rake.application.rake_require "tasks/foo" }

  it "doesn't foo the bar on Mondays" do
    allow(Date.current).to receive(:monday?).and_return(false)
    expect { Rake::Task['foo:bar'].execute }.to raise_error(SystemExit)
  end
end

如果您因特定错误而中止,例如:

name :foo do
  desc 'Runs on mondays'
  task bar: :environment do
    abort "This should only run on a Monday!" unless Date.current.monday?
    # do some special stuff
  end
end

您也可以测试消息,即:

require 'rails_helper'
require 'rake'

RSpec.describe 'FooBar', type: :request do
  before { Rake.application.rake_require "tasks/foo" }

  it "doesn't foo the bar on Mondays" do
    allow(Date.current).to receive(:monday?).and_return(false)
    expect { Rake::Task['foo:bar'].execute }.to raise_error(SystemExit, "This should only run on a Monday!") # The message can also be a regex, e.g. /This should only run/
  end
end

希望这对未来的 Google 员工有所帮助!

【讨论】:

  • 专业提示:如果您使用.invoke,则不会引发错误并且无法挽救。如果您使用.execute,则会引发错误并且可以挽救它。奇怪!
猜你喜欢
  • 2015-12-29
  • 1970-01-01
  • 2014-09-06
  • 2011-10-17
  • 2017-09-24
  • 2011-02-06
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多