Rspec-测试调用“中止”的rake任务

kay*_*zie 6 rake rspec

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

name :foo do
  desc 'Runs on mondays'
  task bar: :environment do
    abort unless Date.current.monday?
    # do some special stuff
  end
end
Run Code Online (Sandbox Code Playgroud)

当我为此 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
Run Code Online (Sandbox Code Playgroud)

最后,我只是将它改为next而不是,abort但我无法在 SO 上或通过谷歌搜索找到这个问题的答案,所以我想我会问。

Pez*_*lio 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

Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

您也可以测试该消息,即:

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

Run Code Online (Sandbox Code Playgroud)

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

  • 专业提示:如果您使用“.invoke”,则不会引发错误且无法挽救。如果您使用“.execute”,则会引发错误并且可以挽救该错误。奇怪的! (2认同)