优化嵌套 RSpec 上下文和示例

Optimizing nested RSpec contexts and examples

我真的很喜欢 RSpec 测试的自我记录性质,所以我经常创建许多嵌套的上下文和示例,以阐明测试对象的意图和测试它们的情况,比如在这个简化的例子中:

RSpec.describe Foo do
  ... some let definitions ...

  context 'when used properly' do
    before do
      something_expensive_to_calculate
    end 

    it 'is successful' do
      ...
    end
    
    it 'has benefits' do
      ....
    end
    
    it 'has the power to change the world' do
      ...
    end
  end

  context 'in evil hands' do
    ... more nested contexts and examples ...
  end
end

然而,这种方法似乎重复了每个示例的设置阶段,因此大大减慢了测试速度。

问题是是否有一些模式允许将文档文本添加到一组断言中(比如我使用 'it'),但不会将上下文设置为 'it'

我找到了 before(:all) 个块。不幸的是 let 变量不能在其中使用,所以这不是我的解决方案。另一种解决方案是让变量具有上下文生命周期,但似乎 RSpec.

中没有这样的东西

我不确定我是否正确理解了你的问题,但也许你正在寻找的是主题语法?

RSpec.describe Foo do
  ... some let definitions ...
  context 'when used properly' do
     subject { do_some stuff } 
        
     it 'whatever' do 
       expect(something).to_not eq true
       expect(subject).to eq false 
     end
  end
end 

主题子句允许您执行一系列与您尝试测试的内容相关的操作,并一遍又一遍地重复使用主题子句中的操作。

TestProf 有一些你似乎需要的东西https://test-prof.evilmartians.io/#/recipes/let_it_be

let_it_be(:foo) { very_expensive_setup }

这将实例化 :foo 一次并为所有示例保持其状态。

确保您也通过 caveates 做好了准备,因为这不仅仅是更好 let