为什么要为 describe 执行 before(:context) ?理想情况下,它应该在规范中的 Context 之前执行

Why is before(:context) executed for describe ? Ideally it should be executed before Context in spec

我想执行一个代码,该代码应该在规范中执行 before(:context)。

我的规范文件:

describe "" do
   context 'test context' do
     it 'test' do
     end
   end
end

我的规范 helper.rb 文件:

RSpec.configure do |config|
  config.before(:context) do |example|
    \ some code which should be executed before context but getting executed during decribe
  end
end

有什么方法可以执行仅在 before(:context) 上运行的代码

contextdescribe 实际上是同一件事(实际上它们都是 example_group 的别名,如此处所述:https://relishapp.com/rspec/rspec-core/v/3-9/docs/example-groups/aliasing

正如您在此处的文档中看到的那样,没有提到 before(:describe)https://relishapp.com/rspec/rspec-core/v/3-9/docs/hooks/before-and-after-hooks

因此,总而言之,您无法完成您想要做的事情。

您可以使用 Filters > Use symbols as metadata 中所示的过滤器,例如:

RSpec.configure do |config|
  config.before(:context, :before_context) do |example|
    # ...
  end
end

只有 context / describe 块指定过滤器将使用它:

describe "" do
  context 'test context', :before_context do
    it 'test' do
      # ...
    end
  end
end

注意:before_context只是一个例子,你可以使用任何符号。