2013-04-12 139 views
0

我已經在互聯網上搜索了很多,以及#2等類似的問題使用RSpec + FactoryGirl嵌套資源的作用,但我仍然不知道如何測試一個嵌套資源的創建方法在我的rails應用程序中。測試「創建」

資源路線

resources :projects, :except => [:index, :show] do 
     resources :mastertags 
end 

這裏是動作我想測試:

def create 
    @mastertag = @project.mastertags.build(params[:mastertag]) 

    respond_to do |format| 
     if @mastertag.save 
     format.html { redirect_to project_mastertags_path, notice: 'Mastertag was successfully created.' } 
     else 
     format.html { render action: "new" } 
     end 
    end 
    end 

這是我與Rspec的測試:

context "with valid params" do 
     it "creates a new Mastertag" do 
     project = Project.create! valid_attributes[:project] 
     mastertag = Mastertag.create! valid_attributes[:mastertag] 
     expect { 
      post :create, { project_id: project.id, :mastertag => valid_attributes[:mastertag] } 
     }.to change(Mastertag, :count).by(1) 
     end 
    end 

我有一個valid_attributes功能:

def valid_attributes 
     { :project => FactoryGirl.attributes_for(:project_with_researcher), :mastertag => FactoryGirl.attributes_for(:mastertag) } 
    end 

我得到以下錯誤:

Failure/Error: post :create, { project_id: project.id, :mastertag => valid_attributes[:mastertag] } 
NoMethodError: 
undefined method `reflect_on_association' for "5168164534b26179f30000a1":String 

我也試過一對夫婦的變化,但似乎沒有任何工作。

回答

0

答案將會在您的FactoryGirl版本上稍有變化。

第一個問題是,@projet是在哪裏創建的?我猜在別的地方?

你既創造項目和mastertag,你爲什麼這樣做?

project = Project.create! valid_attributes[:project] 
mastertag = Mastertag.create! valid_attributes[:mastertag] 

這是當你調用Factory(:project)Factory(:mastertag)

接下來的「笏」 FactoryGirl究竟是幹什麼的,是你在你的規範創建mastertag可言。你不要在任何地方使用該變量。無固定你的問題,你會規格看起來好很多這樣的:

it "creates a new Mastertag" do 
    project = Factory(:project) 
    expect { 
    post :create, { project_id: project.id, :mastertag => Factory.attributes_for(:mastertag)} 
    }.to change(Mastertag, :count).by(1) 
end 

好了,現在我們就完成了清理規範,讓我們看看你的錯誤。

看起來像它在這一行

format.html { redirect_to project_mastertags_path, notice: 'Mastertag was successfully created.' } 

此路徑需要一個項目的ID。

format.html { redirect_to project_mastertags_path(@project), notice: 'Mastertag was successfully created.' } 
0

@John Hinnegan's Answer是絕對正確的。我只想補充一點是很重要的,對項目的標識使用,而不僅僅是項目:

有時候它可能是明顯的使用項目:在參數,但這不工作。

作品:

expect { 
     post :create, { project_id: project.id, :mastertag => valid_attributes[:mastertag] } 
    }.to change(Mastertag, :count).by(1) 

不起作用:

expect { 
     post :create, { project: project.id, :mastertag => valid_attributes[:mastertag] } 
    }.to change(Mastertag, :count).by(1)