Rspec Shared Contexts Have to Be Included Separately (Sometimes)

Let’s say you have two shared_context blocks in your rspec spec that each redefines the same variable or mocks the same method:

shared_context "successful connect" do
  before(:each) do
    allow(ConnectServer).to receive(:connected?) { true } 
  end
... 
end

shared_context "failed connect" do
  before(:each) do
    allow(ConnectServer).to receive(:connected?) { false } 
  end
... 
end

You would expect that including them directly in a parent context would work:

context "current user is provider" do
  before do
   login provider
  end

  include_context "successful connect"
  include_context "failed connect"
end

Well it doesn’t. Due to how rspec (~3.5) is implemented, the two mocks of connected? method overwrite each other, making one of them fail. To avoid that, you have to put each shared_context block in a wrapping context:

context "current user is provider" do
  before do
    login provider
  end

  context "connection succesful" do
    include_context "successful connect"
  end

  context "connection failed" do
    include_context "failed connect"
  end
end