title: RSpec 3: How to stub methods and constants from code we have yet to build/add?
body: <p>We are refactoring a Ruby application called DataSourceIntegrations from a gem we've built called DBQuery.  I am migrating some of the DBQuery code into DataSourceIntegrations.  The section I'm building depends on DBQuery, which will be added in a separate step.</p>
  
  <p>Meanwhile, I need to write RSpec tests to verify that the DBQuery code is being called correctly, all without DBQuery.</p>
  
  <p>What I have is:</p>
  
  <p>Code&mdash;</p>
  
  <p>Gem code&mdash;</p>
  
  <pre><code>module DBQuery
    class Query
      MAX = 1000
  
      def retrieve_users
        # Returns an array of user IDs
      end
    end
  end
  </code></pre>
  
  <p>Application code&mdash;</p>
  
  <pre><code>  module Integration
      def initialize
        @query = DBQuery::Query.new
      end   
    end
  
    module Integration
      class StackOverflowIntegration
        include Integration
  
        def query
          users = []
          while (users &lt; DBQuery::Query::MAX) do
            # Creates a users buffer
            users.push @query.retrieve_users(users_buffer)
          end
        end
      end   
    end
  </code></pre>
  
  <p>Tests&mdash;</p>
  
  <pre><code>describe Integration::StackOverflowIntegration do
    let(:db_query) { double('DBQuery::Query') }
  
    before do
      stub_const('DBQuery::Query::MAX', 1000)
      allow(db_query).to receive(:new).and_return(db_query)
      allow(db_query).to receive(:retrieve_users).and_return([1000, 1001, 1002])
    end
  
    it 'queries without error' do
      expect { StackOverflowIntegration.new.query }.to_not raise_error
    end
  end
  </code></pre>
  
  <p>I can't figure out how to stub in a way that doesn't require DBQuery.  My error is:</p>
  
  <pre><code>NoMethodError:
         undefined method `new' for #&lt;Module:0x007fa7ce561968&gt;
  </code></pre>
  
  <p>I don't know why DBQuery::Query is being represented as a module, or how to get it to recognize "new."</p>