2013-04-12 137 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)