title: rspec shared examples vs shared context
body: <p>What is the real difference between <code>shared_examples</code> and <code>shared_context</code> ?</p>
  
  <p>My observations :</p>
  
  <ol>
  <li><p>I can test same things using both (i.e. with <code>shared_examples</code> or <code>shared_context</code>)</p></li>
  <li><p>But some of my other tests fails if I use later one.</p></li>
  </ol>
  
  <p><strong>Observation #1 :</strong></p>
  
  <p>I compared <a href="https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/example-groups/shared-examples">shared_examples</a> and <a href="https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/example-groups/shared-context">shared_context</a> per documentation on <a href="https://www.relishapp.com/">https://www.relishapp.com/</a></p>
  
  <p>Syntactical differences are :</p>
  
  <ul>
  <li>shared_context to define a block that will be evaluated in the context of example groups by implicitly matching metadata</li>
  </ul>
  
  <p>Example :</p>
  
  <pre><code>shared_context "shared stuff", :a =&gt; :b do
    ...
  end
  </code></pre>
  
  <ul>
  <li>The way these are included or called from a test file</li>
  </ul>
  
  <p>shared_examples</p>
  
  <pre><code>include_examples "name"      # include the examples in the current context
  it_behaves_like "name"       # include the examples in a nested context
  it_should_behave_like "name" # include the examples in a nested context
  </code></pre>
  
  <p>shared_context</p>
  
  <pre><code>include_context "shared stuff"
  </code></pre>
  
  <p><strong>Observation #2</strong></p>
  
  <p>I have a test case</p>
  
  <pre><code>shared_context 'limit_articles' do |factory_name|
    before do
      @account = create(:account)
    end
  
    it 'should restrict 3rd article' do
      create_list(factory_name, 3, account: @account)
  
      article4 = build(factory_name, account: @account)
      article4.should be_invalid
    end
  
    it 'should allow 1st article' do
      ...
    end
  
    it 'should allow 2nd article' do
      ...
    end
  end
  </code></pre>
  
  <p>And include the context in a spec file which already has one shared_context included, then the existing one fails. But I change the order then all my test passes</p>
  
  <p><em>Fails</em></p>
  
  <pre><code>include_context 'existing_shared_context'
  
  include_context 'limit_articles'
  </code></pre>
  
  <p>Also if I replace the <code>shared_context</code> with <code>shared_examples</code> and accordingly include it in test case.</p>
  
  <p><em>Passes</em></p>
  
  <pre><code>include_context 'existing_shared_context'
  
  it_behaves_like 'limit_articles'
  </code></pre>