2014-10-05 3 views
6

레일 4 앱에서 컨트롤러 메소드에 대한 간단한 분리 테스트를 작성하려고합니다. 이 메소드는 쿼리 문자열에서 ID를 가져 와서 Project 모델에 지속성 레이어의 일부 행을 제공하도록 요청하고 그 결과를 JSON으로 렌더링합니다.RSpec에서 class_double을 사용하여 클래스 메소드를 스텁하는 방법은 무엇입니까?

class ProjectsController < ApplicationController 

    def projects_for_company 
    render json: Project.for_company(params[:company_id]) 
    end 

end 

나는 for_company 메서드를 스텁하는 데 어려움을 겪고 있습니다.

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 

내가 for_company 방법을 스텁 한 이후, 나는 메소드의 구현은 무시 기대 : 여기에 내가 노력하고있어 코드입니다. 하지만, 내 모델은 다음과 같습니다 경우 :

class Project < ActiveRecord::Base 

    def self.for_company(id) 
    p "I should not be called" 
    end 

end 

을 ... 그럼 난 I should not be called 실제로 화면에 출력되는 것을 볼 수 있습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

+1

질문의 주위에 원래

class_double("Project").as_stubbed_const 

이것은 정당한 편의 래퍼를 대체 할 as_stubbed_const를 호출 할 수 있습니다 : 당신도 일을하려고했다? 'allow (Project) .to (: for_company) {[project]} '를 받기를 실제로 원했던 것처럼 보입니다. ... –

답변

6

class_double은 실제로 상수를 대체하지 않습니다. 당신은 이전 자체에 stub_const

+0

우수합니다. 매우 감사합니다 :) –

관련 문제