2011-11-08 48 views
2
測試嵌套的控制器動作

我已經路線設置,看起來像:使用RSpec

match '/things/:thing_id' => "descriptions#index", :as => :thing 
resources :things, :except => [:show] do 
    ... 
    resources :descriptions, :only => [:create, :index] 
end 

我將如何測試嵌套描述的:create方法?

到目前爲止,我已經得到了

context "with user signed in" do 

    before(:each) do 
    user = Factory.create(:user, :name => "Bob") 
    controller.stub!(:authenticate_user!).and_return(true) 
    controller.stub!(:current_user).and_return(user) 
    end 

    describe "PUT create" do 

    before(:each) do 
     @thing = Factory.create(:thing) 
     params = {"text" => "Happy Text"} 

     post thing_descriptions_path(@thing.id), params #Doesn't work 
     post :create, params        #Doesn't work 

    end 
    end 
end 
+0

你有這個代碼的規範的名稱是什麼?它是在things_spec還是descriptions_spec中?它應該在後者中。 –

+0

Descriptions_Controller_Spec – Intentss

回答

3

下面應該工作:

describe "PUT create" do 

    before(:each) do 
    @thing = Factory(:thing) 
    attrs = FactoryGirl.attributes_for(:description, :thing_id => @thing) 

    post :create, :thing_id => @thing, :description => attrs 
    end 
end 

要創建你需要告訴RSPEC在後父ID創建一個嵌套的資源,使其能將其插入路線。

您還需要與關係:thing建於創建:descriptions工廠,並且還通過thing_id:description屬性的創建,這是爲了確保工廠女孩不會去創建一個新的:thing時創建:description的屬性,但這不會導致測試失敗,它會降低速度,因爲您最終會創建:thing的兩個實例。