有没有办法在单个blcok中“关闭”共享上下文?

时间:2019-10-30 10:31:30

标签: ruby rspec

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

但是,我有一个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

1 个答案:

答案 0 :(得分:1)

我认为,通过稍微修改您如何包含上下文并使用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