Rspec- 测试调用"abort"的耙子任务



我有一个 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上或通过谷歌搜索找不到这个问题的答案,所以我想我会问。

我知道这是一个旧的,但我一直在研究这个问题,我认为解决这个问题的最佳方法是使用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

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

最新更新