如何使用Rspec使用嵌套路由测试控制器? [英] How to test controllers with nested routes using Rspec?

查看:110
本文介绍了如何使用Rspec使用嵌套路由测试控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个使用脚手架导轨生成器创建的控制器。我希望将它们嵌套在一个名为 demo的文件夹中,然后运行

I have 2 controllers that I created using scaffold generator of rails. I wanted them to be nested in a folder called "demo" and so ran

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

但是此更改导致对用ActionController :: Routing断开的节点进行了rspec测试错误。

But this change resulted on the rspec tests for nodes breaking with ActionController::Routing errors.

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

问题是rspec正在寻找错误的路线。它应该寻找 demo / flows / 1 / nodes。它还需要一个模拟模型来进行流程,但是我不确定如何提供该模型。这是我从生成的rspec文件中获得的示例代码:

The problem is rspec is looking at the wrong route. It's supposed to look for "demo/flows/1/nodes". It also needs a mock model for flow, but I am not sure how to provide that. Here is my sample code from generated rspec file:

  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?

推荐答案

您在这里有两个不同的问题,因此您可能希望将它们分开,因为您的第二个问题与这篇文章的标题无关。我建议使用FactoryGirl创建模拟模型 https://github.com/thoughtbot/factory_girl

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

您的路线错误是由于您的嵌套路线在每个这样的路线之后都需要id的事实造成的:

Your route error is coming from the fact that your nested routes require id's after each one of them like this:

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

何时您对对象进行删除,则需要传递流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.

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.

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

这篇关于如何使用Rspec使用嵌套路由测试控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆