shared_context の使用方法
shared_context を使用して、例グループのコンテキストで評価されるブロックを定義します。include_context を使用して例グループ内でローカルに、または config.include_context を使用してグローバルに共有コンテキストを含めることができます。
共有コンテキストをメタデータによって暗黙的に含める場合、通常は例グループにメタデータを定義する方法が一般的です。この場合、コンテキストはグループ全体に含まれます。ただし、個々の例にも含めることもできます。RSpec は、各例が単一の例グループ(Ruby のシングルトンクラスに類似)を持つものとして扱います。
背景
以下の内容で "shared_stuff.rb" という名前のファイルがあるとします。
RSpec.configure do |rspec|
  # This config option will be enabled by default on RSpec 4,
  # but for reasons of backwards compatibility, you have to
  # set it on RSpec 3.
  #
  # It causes the host group and examples to inherit metadata
  # from the shared context.
  rspec.shared_context_metadata_behavior = :apply_to_host_groups
end
RSpec.shared_context "shared stuff", :shared_context => :metadata do
  before { @some_var = :some_value }
  def shared_method
    "it works"
  end
  let(:shared_let) { {'arbitrary' => 'object'} }
  subject do
    'this is the subject'
  end
end
RSpec.configure do |rspec|
  rspec.include_context "shared stuff", :include_shared => true
end
共有コンテキストを宣言し、include_context でそれを含める
以下の内容で "shared_context_example.rb" という名前のファイルがあるとします。
require "./shared_stuff.rb"
RSpec.describe "group that includes a shared context using 'include_context'" do
  include_context "shared stuff"
  it "has access to methods defined in shared context" do
    expect(shared_method).to eq("it works")
  end
  it "has access to methods defined with let in shared context" do
    expect(shared_let['arbitrary']).to eq('object')
  end
  it "runs the before hooks defined in the shared context" do
    expect(@some_var).to be(:some_value)
  end
  it "accesses the subject defined in the shared context" do
    expect(subject).to eq('this is the subject')
  end
  group = self
  it "inherits metadata from the included context" do |ex|
    expect(group.metadata).to include(:shared_context => :metadata)
    expect(ex.metadata).to include(:shared_context => :metadata)
  end
end
rspec shared_context_example.rb を実行すると、
すべての例がパスするはずです。
共有コンテキストを宣言し、include_context でそれを含め、追加のブロックで拡張する
以下の内容で "shared_context_example.rb" という名前のファイルがあるとします。
require "./shared_stuff.rb"
RSpec.describe "including shared context using 'include_context' and a block" do
  include_context "shared stuff" do
    let(:shared_let) { {'in_a' => 'block'} }
  end
  it "evaluates the block in the shared context" do
    expect(shared_let['in_a']).to eq('block')
  end
end
rspec shared_context_example.rb を実行すると、
すべての例がパスするはずです。