简体   繁体   English

如何使用 Rspec 测试具有嵌套路由的控制器?

[英]How to test controllers with nested routes using Rspec?

I have 2 controllers that I created using scaffold generator of rails.我有 2 个控制器,它们是使用脚手架生成器创建的。 I wanted them to be nested in a folder called "demo" and so ran我希望它们嵌套在一个名为“demo”的文件夹中,然后运行

rails g scaffold demo/flows
rails g scaffold demo/nodes

Then I decided to nest nodes inside flows, and changed my routes file like so:然后我决定在流中嵌套节点,并像这样更改我的路由文件:

namespace :demo do 
  resources :flows do
    resources :nodes
  end
end

But this change resulted on the rspec tests for nodes breaking with ActionController::Routing errors.但是这种更改导致 rspec 测试节点因 ActionController::Routing 错误而中断。

  15) Demo::NodesController DELETE destroy redirects to the demo_nodes list
     Failure/Error: delete :destroy, :id => "1"
     ActionController::RoutingError:
       No route matches {:id=>"1", :controller=>"demo/nodes", :action=>"destroy"}

The problem is rspec is looking at the wrong route.问题是 rspec 正在寻找错误的路线。 It's supposed to look for "demo/flows/1/nodes".它应该寻找“demo/flows/1/nodes”。 It also needs a mock model for flow, but I am not sure how to provide that.它还需要一个模拟 model 用于流程,但我不知道如何提供。 Here is my sample code from generated rspec file:这是我生成的 rspec 文件中的示例代码:

  def mock_node(stubs={})
    @mock_node ||= mock_model(Demo::Node, stubs).as_null_object
  end

  describe "GET index" do
    it "assigns all demo_nodes as @demo_nodes" do
      Demo::Node.stub(:all) { [mock_node] }
      get :index
      assigns(:demo_nodes).should eq([mock_node])
    end
  end

Can someone help me understand how I need to provide the flow model?有人可以帮助我了解我需要如何提供流程 model 吗?

You have two different questions going on here, so you may want to split them up since your second question has nothing to do with the title of this post.您在这里有两个不同的问题,因此您可能希望将它们分开,因为您的第二个问题与这篇文章的标题无关。 I would recommend using FactoryGirl for creating mock models https://github.com/thoughtbot/factory_girl我建议使用 FactoryGirl 创建模拟模型https://github.com/thoughtbot/factory_girl

Your route error is coming from the fact that your nested routes require id's after each one of them like this:您的路由错误来自这样一个事实,即您的嵌套路由在每个路由之后都需要 id,如下所示:

/demo/flows/:flow_id/nodes/:id

When you do the delete on the object, you need to pass in the flow ID or else it won't know what route you are talking about.当你在 object 上进行删除时,你需要传入流 ID,否则它不会知道你在说什么路由。

delete :destroy, :id => "1", :flow_id => "1"

In the future, the easiest way to check what it expects is to run rake routes and compare the output for that route with what you params you are passing in.将来,检查它所期望的最简单的方法是运行rake routes并将该路由的 output 与您传入的参数进行比较。

demo_flow_node  /demo/flows/:flow_id/nodes/:id(.:format)   {:action=>"destroy", :controller=>"demo/flows"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM