2010-03-31 49 views
10

我有兩個型號:RSpec的,磕碰嵌套資源的方法

class Solution < ActiveRecord::Base 
    belongs_to :owner, :class_name => "User", :foreign_key => :user_id 
end 

class User < ActiveRecord::Base 
    has_many :solutions 
end 

和我窩解決方案的用戶中像這樣:

ActionController::Routing::Routes.draw do |map| 
    map.resources :users, :has_many => :solutions 
end 

,並終於在這裏就是我「米試圖符合規範的動作:?

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 

我的問題是,如何赫克我SPEC @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

看起來像我找到了我自己的答案,但我會在這裏發佈它,因爲我似乎無法在網上找到很多關於此的信息。

的RSpec有一個方法叫stub_chain:http://apidock.com/rspec/Spec/Mocks/Methods/stub_chain

這使得它易於存根等的方法:通過這樣

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

:所以

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

然後我可以寫一個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 

我的規範通過。不過,我仍然在這裏學習,所以如果有人認爲我的解決方案不好,請隨時評論這一點,我試圖讓它完全正確。

+0

非常有幫助,謝謝鏈。 – zetetic

+0

歡迎您,只需將答案投票! – TheDelChop

7

隨着新RSpec的語法,你存根像這樣

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