gpt4 book ai didi

ruby - 如何干燥在多个上下文中重复的测试用例?

转载 作者:数据小太阳 更新时间:2023-10-29 08:03:28 24 4
gpt4 key购买 nike

我猴子修补了 URI 并为它编写了测试:

describe URI do
describe '.sanitize_domain' do
let(:expectation) { 'toolbar.google.com' }
subject { described_class.sanitize_domain(url) }

context 'when url is correct' do
context 'when url misses both http and www prefixes' do
let(:url) { 'toolbar.google.com/public' }
it { is_expected.to eq(expectation) }
end

context 'when url contains www' do
let(:url) { 'www.toolbar.google.com/public' }
it { is_expected.to eq(expectation) }
end

context 'when url contains https' do
let(:url) { 'https://toolbar.google.com/public' }
it { is_expected.to eq(expectation) }
end

context 'when url contains both http and www' do
let(:url) { 'http://www.toolbar.google.com/public' }
it { is_expected.to eq(expectation) }
end

context 'when multiple urls are given' do
let(:url) { 'http://www.toolbar.google.com/Default.asp, http://www.toolbar.google.com/' }
it { is_expected.to eq(expectation) }
end
end
end
end

如您所见,it { is_expected.to eq(expectation) } 在每个上下文中重复。

我认为有一个解决方案可以让它变干一点。我可以在这里使用 shared_examples,但恕我直言,对单个 it 这样做就太过分了,而且可读性会降低。

我试图将 expectation 提取到 before(:context) { it { is_expected } } it 关键字在内部不可用之前 block 。这是该尝试的错误消息:

it is not available from within an example (e.g. an it block) or from constructs that run in the scope of an example (e.g. before, let, etc). It is only available on an example group (e.g. a describe or context block).

最佳答案

inner_contextes_urls = [
['when url misses both http and www prefixes', 'toolbar.google.com/public'],
['when url contains www', 'www.toolbar.google.com/public']
# ...
]
inner_contextes_urls.each do |(title, url)|
context "#{title}" do
let(:url) { "#{url}" }
it { is_expected.to eq(expectation) }
end
end

关于ruby - 如何干燥在多个上下文中重复的测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32331374/

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