gpt4 book ai didi

ruby-on-rails - 在 RSpec 中访问主题层次结构的模式

转载 作者:行者123 更新时间:2023-12-04 03:02:06 24 4
gpt4 key购买 nike

当使用 RSpec 测试深度嵌套的数据结构时,我发现需要根据包含上下文中的主题来定义嵌套上下文中的主题。我已经广泛查看,但没有找到任何关于如何在不定义许多变量的情况下进行处理的示例。它使规范复杂化并限制了规范重用的可能性。我很好奇在 RSpec 中是否有办法做到这一点,如果没有,解决这个问题的好方法是什么。

现在,我的代码看起来像:

context 'with a result which is a Hash' do
before do
@result = get_result()
end
subject { @result }
it { should be_a Hash }
context 'with an Array' do
before do
@array_elem = @result[special_key]
end
subject { @array_elem }
it { should be_an Array }
context 'that contains a Hash' do
before do
@nested_hash = ...
end
subject { @nested_hash }
...
end
end
end

相反,我宁愿写一些类似的东西:
context 'with a result which is a Hash' do
subject { get_result }
it { should be_a Hash }
context 'with an Array' do
subject { parent_subject[special_key] }
it { should be_an Array }
context 'that contains a Hash' do
subject { do_something_with(parent_subject) }
...
end
end
end

使用这种类型的自动主题层次结构管理扩展 RSpec 的方法是什么?

最佳答案

在这种层次结构中,我实际上会放弃使用 subject并使主题明确。虽然这可能会导致更多的输入(如果你有很多测试),但它也更清晰。
嵌套subject如果您向下三个级别,语句也可能会混淆实际正在测试的内容。

  context 'with a result which is a Hash' do
before do
@result = get_result()
end
it { @result.should be_a Hash }
context 'special_key' do
before do
@array_elem = @result[special_key]
end
it { @array_elem.should be_an Array }
context 'that contains a Hash' do
before do
@nested_hash = ...
end
it { @nested_hash.should be_a Hash }
...
end
end
end

但这可能是一个品味问题。
希望这可以帮助。

关于ruby-on-rails - 在 RSpec 中访问主题层次结构的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7524786/

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