【问题标题】:Don't execute the before test code for every test without using a before all block不要在不使用 before all 块的情况下为每个测试执行测试前代码
【发布时间】:2019-01-23 08:41:06
【问题描述】:

我想执行一些之前的代码并使用多个 it 语句测试结果,而不必运行之前的代码。

context 'context A' do
   context 'context A.1' do
     before(:each) do
        # Doing a lot of things and using let variables,...
     end

     it 'T1: test thing 1'
     it 'T2: test thing 2'
     it 'T3: test thing 3'
  end

  context 'context B.1' do
     before(:each) do
        # Doing a lot of things and using let variables,...
     end

     it 'T1: test thing 1'
     it 'T2: test thing 2'
     it 'T3: test thing 3'
  end
end

如果你看一下执行,它看起来像:

在 A.1 之前 - T1 - 在 A.1 之前 - T2 - 在 A.1 之前 - T3 - 在 B.1 之前 - T1 - ...

但我想要:

A.1 之前 - T1 - T2 - T3 - B.1 之前 - T1 - T2 - T3

我尝试使用 before(:all) 但我不能使用它,因为我使用了很多 let 变量。您会收到以下错误,因为 let 应该在每种情况下都发生变化。

RuntimeError: let 声明 var1before(:context) 钩子中访问:

我可以在一个 it 语句中组合所有测试,但我不希望这样,我想看看哪个部分测试失败。我看到的唯一解决方案是摆脱所有 let 变量,但这会导致大量实例变量和许多不同的测试文件导致大量重复代码...

我可以通过其他方式获得我想要的行为吗?还是我必须以另一种方式看待事物?

【问题讨论】:

  • 我不明白为什么删除 let 变量(用实例变量替换它们)会导致行长增加。定义实例变量占用的空间不超过let
  • 是的,我应该说很多实例变量应该在文档和很多其他测试文件中声明。我不喜欢,因为如果发生变化,它会产生很多重复的代码和更多的维护......

标签: ruby rspec automated-tests


【解决方案1】:

但我不想这样,我想看看哪个部分测试失败。

这是阻止你这样做的唯一原因吗?很简单。

   context 'context A.1' do
     before(:each) do
        # Doing a lot of things and using let variables,...
     end

     it 'test all the things', aggregate_failures: true do
       ... 
     end

  end

您甚至可以为 spec_helper.rb 中的所有规范全局启用它(我就是这样做的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 2021-09-11
    • 2011-06-13
    相关资源
    最近更新 更多