2015-10-12 134 views
1

我自学写控制器测试,并正在此得到这个错误:Rails的控制器测试:ActionController的:: UrlGenerationError:没有路由匹配

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') doput :update, post: {title: 'My Post', body: 'Updated Ipsum’}

回答

0

你需要一个id传递给update行动:

put :update, id: <THE ID HERE>, post: {title: 'My Post', body: 'Updated Ipsum'}

+0

非常感谢。作为'@ post.id',我在''中通过我的夹具。这解决了问题。 – Storycoder

0

根据您的控制器中的update动作,您需要在params中通过postid

所以,在您的测试,建立你params哈希是这样的:

let(:update_query_parameters) { { post: { title: 'My Post', body: 'Updated Ipsum' }, id: post.id } } 

然后,使用update_query_parameters通过为paramsput :update方法:

test "should update post" do 
    assert_difference('Post.count') do 
    put :update, update_query_parameters 
    end 

    assert_redirected_to post_path(assigns(:post)) 
end 
+0

感谢您的帮助。我没有通过身份证。在您和其他评论者的帮助之前,我不知道我需要解决的问题。我没有使用你的过程,但是我感谢你确实把重点放在了正确的问题上。 – Storycoder

0

得益于两位评论者以上,我能够理解我需要解决的问题:我需要在我的更新测试中传递一个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 
相关问题