title: Is there a way to stub a method of an included module with Rspec?
body: <p>I have a module that is included in another module, and they both implement the same method.
  I would like to stub the method of the included module, something like this:</p>
  
  <pre><code>module M
    def foo
      :M
    end
  end
  
  module A
    class &lt;&lt; self
      include M
  
      def foo
        super
      end
    end
  end
  
  describe "trying to stub the included method" do
    before { allow(M).to receive(:foo).and_return(:bar) }
  
    it "should be stubbed when calling M" do
      expect(M.foo).to eq :bar
    end
  
    it "should be stubbed when calling A" do
      expect(A.foo).to eq :bar
    end
  end
  </code></pre>
  
  <p>The first test is passing, but the second one outputs:</p>
  
  <pre><code>Failure/Error: expect(A.foo).to eq :bar
  
     expected: :bar
          got: :M
  </code></pre>
  
  <p>Why isn't the stub working in this case?
  Is there a different way to achieve this?</p>
  
  <p>Thanks!</p>
  
  <p>-------------------------------------UPDATE----------------------------------</p>
  
  <p>Thanks! using allow_any_instance_of(M) solved this one.
  My next question is - what happens if I use prepend and not include? see the following code:</p>
  
  <pre><code>module M
    def foo
      super
    end
  end
  
  module A
    class &lt;&lt; self
      prepend M
  
      def foo
        :A
      end
    end
  end
  
  describe "trying to stub the included method" do
    before { allow_any_instance_of(M).to receive(:foo).and_return(:bar) }
  
    it "should be stubbed when calling A" do
      expect(A.foo).to eq :bar
    end
  end 
  </code></pre>
  
  <p>This time, using allow_any_instance_of(M) results in an infinite loop. why is that? </p>