gpt4 book ai didi

Rspec-测试调用 "abort"的 rake 任务

转载 作者:行者123 更新时间:2023-12-03 14:48:34 24 4
gpt4 key购买 nike

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

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

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

我的问题是:在测试中是否有可能以某种方式“ stub ”中止,以便它继续运行其他测试,或者我别无选择,只能使用另一种方法退出 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

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

关于Rspec-测试调用 "abort"的 rake 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57531576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com