首页 > 解决方案 > 为什么为 describe 执行 before(:context) ?理想情况下,它应该在规范中的 Context 之前执行

问题描述

我想执行一个应该在规范中执行 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) 上运行的代码

标签: rubyrspec

解决方案


您可以使用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只是一个示例,您可以使用任何符号。


推荐阅读