【问题标题】:Rails 4 testing nested resources with multiple URL paramsRails 4 使用多个 URL 参数测试嵌套资源
【发布时间】:2016-02-01 05:25:17
【问题描述】:

我已经在这几个小时了,仍然无法弄清楚。我对嵌套资源控制器上的 2 个操作进行了 2 个测试。 requests 是父资源路由,response 是嵌套资源路由。

这两个测试给了我一个no route matches 错误。没有意义。在第一个测试中,它尝试运行update 操作而不是edit。这是我的测试:

test "should get edit" do
  assert_routing edit_request_response_path(@myresponse.request_id, @myresponse), { :controller => "responses", :action => "edit", :request_id => @myresponse.request_id.to_s, :id => @myresponse.id.to_s }
  get :edit, params: { id: @myresponse, request_id: @myresponse.request_id }
  assert_response :success
end

test "should update response" do
  post :update, :request_id => @myresponse.request_id, response: { body: @myresponse.body, request_id: @myresponse.request_id, status: @myresponse.status, subject: @myresponse.subject, user_id: @myresponse.user_id }
  assert_redirected_to response_path(assigns(:response))
end

以下是错误:

3) Error:
ResponsesControllerTest#test_should_get_edit:
ActionController::UrlGenerationError: No route matches {:action=>"edit", :controller=>"responses", :params=>{:id=>"980190962", :request_id=>"999788447"}}
test/controllers/responses_controller_test.rb:43:in `block in <class:ResponsesControllerTest>'


4) Error:
ResponsesControllerTest#test_should_update_response:
ActionController::UrlGenerationError: No route matches {:action=>"update", :controller=>"responses", :request_id=>"999788447", :response=>{:body=>"This is the body", :request_id=>"999788447", :status=>"draft", :subject=>"This is the subject", :user_id=>"175178709"}}
test/controllers/responses_controller_test.rb:48:in `block in <class:ResponsesControllerTest>'

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing ruby-on-rails-4 testing


    【解决方案1】:

    在这种情况下,您可能希望使用浅嵌套,因为如果您可以通过/response/:id 获得响应,则没有理由通过request

    resources :requests, shallow: true do
      resources :response
    end
    

    test "should get edit" do
      assert_routing edit_response_path(@myresponse), { :controller => "responses", :action => "edit", :id => @myresponse.id.to_s }
      get :edit, params: { id: @myresponse, request_id: @myresponse.request_id }
      assert_response :success
    end
    

    但是,将业务逻辑对象命名为 RequestResponse 是一个很大的错误。这些已经是 Rails 中的关键概念,它们对应于来自客户端的请求和通过 rails 发送给客户端的响应。

    您最终会混淆自己和必须从事该项目的任何可怜的傻瓜。此外,您最终将屏蔽 requestresponse 方法,它们是 ActionController API 中非常重要的部分。

    改用其他同义词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多