[英]ActionController::UrlGenerationError: No route matches action and controller
[英]Rails Controller Testing: ActionController::UrlGenerationError: No route matches
我正在自學編寫控制器測試,並得到此錯誤:
ERROR["test_should_update_post", PostsControllerTest, 2015-10-11 12:12:31 -0400]
test_should_update_post#PostsControllerTest (1444579951.69s)
ActionController::UrlGenerationError: ActionController::UrlGenerationError: No route matches {:action=>"update", :controller=>"posts", :post=>{:title=>"My Post", :body=>"Updated Ipsum"}}
test/controllers/posts_controller_test.rb:51:in `block (2 levels) in <class:PostsControllerTest>'
test/controllers/posts_controller_test.rb:50:in `block in <class:PostsControllerTest>’
這是我的測試:
test "should update post" do
assert_difference('Post.count') do
put :update, post: {title: 'My Post', body: 'Updated Ipsum'}
end
assert_redirected_to post_path(assigns(:post))
end
這是我的yaml:
entry_one:
title: "Foobar"
body: "Ipsum This"
entry_two:
title: "Barfoo"
body: "This Ipsum"
這是我的控制器:
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to @post, notice: 'Event updated successfully'
else
render :edit
end
end
您能指出我需要解決的問題嗎?
我可以從錯誤和行數看出來,這與以下assert_difference('Post.count') do
行有關: assert_difference('Post.count') do
並put :update, post: {title: 'My Post', body: 'Updated Ipsum'}
您需要將id
傳遞給update
操作:
put :update, id: <THE ID HERE>, post: {title: 'My Post', body: 'Updated Ipsum'}
根據您控制器中的update
操作,您需要在params
傳遞post
的id
。
因此,在測試中,按如下所示構建params
哈希:
let(:update_query_parameters) { { post: { title: 'My Post', body: 'Updated Ipsum' }, id: post.id } }
然后,使用update_query_parameters
作為put :update
方法的params
傳遞:
test "should update post" do
assert_difference('Post.count') do
put :update, update_query_parameters
end
assert_redirected_to post_path(assigns(:post))
end
感謝上面的兩個評論者,我能夠理解我需要解決的問題:我需要在更新測試中傳遞一個id。
我已經在同一個應用程序的類似編輯測試中完成了此操作,我確切知道該嘗試什么。
我以前在測試中使用了設置方法,將上面共享的yaml傳遞到測試中:
def setup
@post = posts(:entry_one)
end
通過這種方法,我可以將@ post.id傳遞到我的更新測試中,並使其通過:
test "should update post" do
assert_no_difference('Post.count') do
put :update, id: @post.id, post: {title: 'My Post', body: 'Updated Ipsum'}
end
assert_redirected_to post_path(assigns(:post))
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.