有没有办法在单个块中 "turn off" 共享上下文?

Is there a way to "turn off" a shared context inside a single blcok?

我正在使用共享上下文来 DRY 我的规范文件。

但是,我有一个 context 块,我想在其中禁用共享上下文。这可能吗?

describe MyClass do
  include_context 'my shared context'

  describe '#some_method' do
    # Specs using the shared context...

    context 'with some special context' do
      # Turn off 'my shared context' here      
      # ...
    end
  end
end

我认为通过稍微修改您包含上下文的方式并使用 RSpec 元数据,您应该能够使它正常工作。

RSpec.shared_context "my shared context" do
  # code
end



# spec/support/shared_context_load.rb
RSpec.configure do |config|
  config.before do |example|
    unless example.metadata[:load_shared_context] == false
      config.include_context "my shared context"
    end
  end
end



describe MyClass do
  # NOTE the shared_contxet is removed from here

  describe '#some_method' do
    # Specs using the shared context...

    it "this spec using shared context"
       # code
    end

    context 'with some special context' do
      it "this spec is not using shared context", load_shared_context: false do 
        # Turn off 'my shared context' here      
        # ...
      end
    end
  end
end