title: How do I stub a class method with a class_double in RSpec?
body: <p>I’m trying to write a simple isolated test for a controller method in my Rails 4 app. The method takes an ID from a query string, asks the <code>Project</code> model to give me some rows from the persistence layer, and render the result as JSON.</p>
  
  <pre><code>class ProjectsController &lt; ApplicationController
  
    def projects_for_company
      render json: Project.for_company(params[:company_id])
    end
  
  end
  </code></pre>
  
  <p>I’m struggling with stubbing the <code>for_company</code> method. Here is the code I’m trying:</p>
  
  <pre><code>require "rails_helper"
  
  describe ProjectsController do
  
    describe "GET #projects_for_company" do
  
      it "returns a JSON string of projects for a company" do
        dbl = class_double("Project")
        project = FactoryGirl.build_stubbed(:project)
        allow(dbl).to receive(:for_company).and_return([project])
        get :projects_for_company
        expect(response.body).to eq([project].to_json)
      end
  
    end
  
  end
  </code></pre>
  
  <p>Since I’ve stubbed the <code>for_company</code> method, I expect the implementation of the method to be ignored. However, if my model looks like this:</p>
  
  <pre><code>class Project &lt; ActiveRecord::Base
  
    def self.for_company(id)
      p "I should not be called"
    end
  
  end
  </code></pre>
  
  <p>…Then I can see that <code>I should not be called</code> is actually printed to the screen. What am I doing wrong?</p>