我已經在互聯網上搜索了很多,以及#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
我也試過一對夫婦的變化,但似乎沒有任何工作。