2010-03-31 1 views
10

스텁 나는 두 가지 모델을 가지고 :RSpec에는 중첩 된 자원의 방법

class SolutionsController < ApplicationController 
    before_filter :load_user 

    def show 
    if(@user) 
     @solution = @user.solutions.find(params[:id]) 
    else 
     @solution = Solution.find(params[:id]) 
    end 
    end 

    private 

    def load_user 
    @user = User.find(params[:user_id]) unless params[:user_id].nil? 
    end 
end 

내 질문은, 도대체 내가 사양 어떻게 @user.solutions.find(params[:id])

여기에 내 현재의 사양입니다 :

describe SolutionsController do 

    before(:each) do 
    @user = Factory.create(:user) 
    @solution = Factory.create(:solution) 
    end 

    describe "GET Show," do 

    before(:each) do 
     Solution.stub!(:find).with(@solution.id.to_s).and_return(@solution) 
     User.stub!(:find).with(@user.id.to_s).and_return(@user) 
    end 

    context "when looking at a solution through a user's profile" do 

     it "should find the specified solution" do 
     Solution.should_receive(:find).with(@solution.id.to_s).and_return(@solution) 
     get :show, :user_id => @user.id, :id => @solution.id 
     end 
    end 
    end 

그러나 그것은 나에게 다음과 같은 오류 가져옵니다

1)Spec::Mocks::MockExpectationError in 'SolutionsController GET Show, when looking at a solution through a user's profile should find the specified solution' 
<Solution(id: integer, title: string, created_at: datetime, updated_at: datetime, software_file_name: string, software_content_type: string, software_file_size: string, language: string, price: string, software_updated_at: datetime, description: text, user_id: integer) (class)> received :find with unexpected arguments 
    expected: ("6") 
    got: ("6", {:group=>nil, :having=>nil, :limit=>nil, :offset=>nil, :joins=>nil, :include=>nil, :select=>nil, :readonly=>nil, :conditions=>"\"solutions\".user_id = 34"}) 

사람이 내가 @user.solutions.new(params[:id]) 스텁 수있는 방법으로 도와 줄 수 있습니까?

답변

25

내 자신의 답변을 찾은 것처럼 보이지만 그물에 대해 전체적으로 많은 것을 찾지 못했기 때문에 여기에 게시 할 것입니다. http://apidock.com/rspec/Spec/Mocks/Methods/stub_chain

쉽게 같은 방법 스텁 할 수 있습니다 : 다음 내가 쓸 수 그래서

@user.stub_chain(:solutions, :find).with(@solution.id.to_s).and_return(@solution) 

:이 작업을 수행하여

@solution = @user.solutions.find(params[:id]) 

RSpec에이 방법이라고 stub_chain있다 다음과 같은 RSpec 테스트 :

it "should find the specified solution" do 
    @user.solutions.should_receive(:find).with(@solution.id.to_s).and_return(@solution) 
    get :show, :user_id => @user.id, :id => @solution.id 
end 

내 사양이 통과합니다. 그러나 나는 여전히 여기에서 배우고 있기 때문에 아무도 나의 해결책이 좋지 않다고 생각한다면,이 말을 자유롭게 생각해보고 나는 그것을 완전히 바르게하려고 노력한다. 새로운 RSpec에 구문 조

+0

매우 도움이, 감사 등의 체인점을 스텁. – zetetic

+0

환영합니다, 그냥 답을 부탁합니다! – TheDelChop

7

, 당신은 너무

allow(@user).to receive_message_chain(:solutions, :find) 
# or 
allow_any_instance_of(User).to receive_message_chain(:solutions, :find)