我正在尝试解决以下错误:
ElementsControllerTest#test_should_get_create:
ActionController::UrlGenerationError: No route matches {:action=>"create", :controller=>"elements"}
test/controllers/elements_controller_test.rb:15:in `block in <class:ElementsControllerTest>'
Element
是嵌套资源(Piece的子级)
resources :batiments do
resources :pieces
end
resources :pieces, shallow: true do
resources :elements
end
测试/控制器/ elements_controller.rb
class ElementsController < ApplicationController
#after_filter :load_piece
def index
@piece = Piece.find(params[:piece_id])
@elements = @piece.elements.all
end
def new
@piece = Piece.find(params[:piece_id])
@element = @piece.elements.new
end
def create
@piece = Piece.find(params[:piece_id])
@element = @piece.elements.new(element_params)
if @element.save
flash[:notice] = "Elément créé!"
else
flash[:alert] = "Elément non créé!"
end
redirect_to piece_path(@piece)
end
…
end
和我的元素路线:
Prefix Verb URI Pattern Controller#Action
piece_elements GET /pieces/:piece_id/elements(.:format) elements#index
POST /pieces/:piece_id/elements(.:format) elements#create
new_piece_element GET /pieces/:piece_id/elements/new(.:format) elements#new
edit_element GET /elements/:id/edit(.:format) elements#edit
element GET /elements/:id(.:format) elements#show
PATCH /elements/:id(.:format) elements#update
PUT /elements/:id(.:format) elements#update
DELETE /elements/:id(.:format) elements#destroy
pieces GET /pieces(.:format) pieces#index
POST /pieces(.:format) pieces#create
new_piece GET /pieces/new(.:format) pieces#new
edit_piece GET /pieces/:id/edit(.:format) pieces#edit
piece GET /pieces/:id(.:format) pieces#show
PATCH /pieces/:id(.:format) pieces#update
PUT /pieces/:id(.:format) pieces#update
DELETE /pieces/:id(.:format) pieces#destroy
更新:/ strong中的 elements_controller_test.rb
require 'test_helper'
class ElementsControllerTest < ActionController::TestCase
test "should get create" do
get :create
assert_response :success
end
end
答案 0 :(得分:2)
更改您的测试用例如下:
class ElementsControllerTest < ActionController::TestCase
test "should get create" do
post :create, element: {attrb1: "value", attrb2: "value"}, piece_id: id_of_existing_piece_record ## Post method
assert_response :success
end
end
create
是post
路线而不是get
路线。这就是您收到No route matches {:action=>"create", :controller=>"elements"}
错误的原因
此外,由于elements
嵌套在pieces
中,您必须将现有作品的ID传递给post :create
来电。
element: {attrb1: "value", attrb2: "value"}
用于您要在元素记录中保存的属性。