我在互联网上搜索了很多东西以及关于 Stackoverflow 的其他类似问题,但是我仍然不确定如何在我的 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
我也尝试了几种变体,但似乎没有任何效果。