【问题标题】:Rails Controller Testing: ActionController::UrlGenerationError: No route matchesRails 控制器测试:ActionController::UrlGenerationError:没有路由匹配
【发布时间】:2015-10-12 01:31:45
【问题描述】:

我正在自学编写控制器测试,却遇到了这个错误:

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’}

【问题讨论】:

    标签: ruby-on-rails controller


    【解决方案1】:

    您需要将id 传递给update 操作:

    put :update, id: &lt;THE ID HERE&gt;, post: {title: 'My Post', body: 'Updated Ipsum'}

    【讨论】:

    • 非常感谢。我在&lt;THE ID HERE&gt; 中以@post.id 传递了我的夹具。这解决了问题。
    【解决方案2】:

    根据您在控制器中的update 操作,您需要在params 中传递postid

    因此,在您的测试中,像这样构建您的 params 哈希:

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

    然后,使用update_query_parameters 作为params 传递您的put :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
    

    【讨论】:

    • 感谢您的帮助。我没有传递身份证。在您和其他评论者的帮助之前,我不知道我需要解决的问题。我没有使用您的流程,但感谢您,我确实专注于正确的问题。
    【解决方案3】:

    感谢上面的两位评论者,我能够理解我需要解决的问题:我需要在更新测试中传递一个 id。

    我已经在同一个应用程序的类似编辑测试中完成了这项工作,我完全知道要尝试什么。

    我之前在测试中使用了 setup 方法将上面共享的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多