title: Stub ActiveRecord::Relation with ActiveRecord objects
body: <p>I'm not testing a Rails app. Just getting that out of the way.</p>
  
  <p>I'm testing a library that connects to a relatively active server, restricting records by timestamp. These returned records change as time goes on, making testing other restrictions more complicated. I need to stub out the <code>ActiveRecord::where</code> method to return my own custom relation with objects I create to meet the criteria I need.</p>
  
  <p>Something like</p>
  
  <pre><code>relation = double(ActiveRecord::Relation)
  relation.stub(:[]).and_return( [MyClass.new(...), MyClass.new(...), ...] )
  MyClass.stub(:where).and_return( relation )
  </code></pre>
  
  <p>is what I'd like, but that doesn't work. I need it to be an <code>ActiveRecord::Relation</code> because I need to be able to call <code>ActiveRecord::where</code> and <code>ActiveRecord::select</code> on the object in the code.</p>
  
  <hr>
  
  <p><strong>Edit 2014-01-28</strong></p>
  
  <p>In lib/call.rb</p>
  
  <pre><code>class Call &lt; ActiveRecord::Base
    class &lt;&lt; self
      def sales start_time, end_time
        restricted_records = records(start_time, end_time, :agent_id)
        #other code
      end
  
      #other methods
  
      private
  
        def records start_time, end_time, *select
          # I'm leaving in commented code so you can see why I want the ActiveRecord::Relation object, not an Array
          calls = Call.where("ts BETWEEN '#{start_time}' AND '#{end_time}'") #.select(select)
          raise calls.inspect
            #.to_a.map(&amp;:serializable_hash).map {|record| symbolize(record)}
        end
    end
  end
  </code></pre>
  
  <p>In spec/call_spec.rb</p>
  
  <pre><code>require 'spec_helper'
  require 'call.rb'
  
  describe Call do
    let(:period_start) { Time.now - 60 }
    let(:period_end) { Time.now }
  
    describe "::sales" do
      before do
        relation = Call.all
        relation.stub(:[]).and_return( [Call.new(queue: "12345")] )
        Call.stub(:where).and_return( relation )
      end
  
      subject { Call.sales(period_start, period_end) }
  
      it "restricts results to my custom object" do
        subject
      end
    end
  end
  </code></pre>
  
  <p>Output from test:</p>
  
  <pre><code>RuntimeError:
    #&lt;ActiveRecord::Relation [ #an array containing all the actual Call records, not my object ]&gt;
  </code></pre>