2011-05-20 138 views
17

我找不到任何解释如何在Rails 3中测试路由的东西。即使在Rspec的书中,它也不能很好地解释。如何在Rails 3中用Rspec 2测试路由?

感谢

+0

[示例Rspec路由](https://cbabhusal.wordpress.com/2015/12/15/rails-rspec-examples-of-routing-specs/#more-1623) – illusionist 2015-12-15 03:33:21

回答

32

上有rspec-rails Github site一个简单的例子。您也可以使用脚手架生成器来生成一些罐头示例。例如,

rails g scaffold Article

应该产生这样的:

require "spec_helper" 

describe ArticlesController do 
    describe "routing" do 

    it "routes to #index" do 
     get("/articles").should route_to("articles#index") 
    end 

    it "routes to #new" do 
     get("/articles/new").should route_to("articles#new") 
    end 

    it "routes to #show" do 
     get("/articles/1").should route_to("articles#show", :id => "1") 
    end 

    it "routes to #edit" do 
     get("/articles/1/edit").should route_to("articles#edit", :id => "1") 
    end 

    it "routes to #create" do 
     post("/articles").should route_to("articles#create") 
    end 

    it "routes to #update" do 
     put("/articles/1").should route_to("articles#update", :id => "1") 
    end 

    it "routes to #destroy" do 
     delete("/articles/1").should route_to("articles#destroy", :id => "1") 
    end 

    end 
end 
+1

https://github.com/rspec/rspec-rails#routing-specs可能会有所帮助 – 2012-12-06 18:41:50

+0

我有这些类型的测试问题,这是我的问题http://stackoverflow.com/questions/14330293/rspec-for-routes-and-testing- routes-rb-specific#comment19916220_14330293,它几乎不验证路由是否存在于routes.rb中,它只与syntanx检查一起使用。有任何想法吗? – Matilda 2013-01-15 03:32:41

-8

探究性的回答解释了如何测试路线。这个答案解释了为什么你不应该那样做。

一般情况下,您的测试应该测试行为暴露给用户(或客户端对象),而不是实施通过提供这种行为。路由是面向用户的:当用户键入http://www.mysite.com/profile时,他不关心它到ProfilesController;相反,他关心他看到他的个人资料。

所以不要测试你要去ProfilesController。相反,建立一个黄瓜场景来测试当用户去/profile时,他看到他的名字和个人资料信息。这就是你需要的。

再次:不测试你的路线。测试你的行为。

+2

如果有人对此进行了低估,那将会很好,因为他们会解释为什么他们这么做...... – 2011-12-05 02:40:19

+3

因为根据你的定义,所有的单元测试都是毫无意义的? – sevenseacat 2012-01-09 05:58:17

+1

一般不会。单元测试在模型层面非常有用 - 涉及内部业务逻辑(独立于用户界面)。然而,在控制器层面,只有UI是相关的,所以测试控制器的实现并不能告诉你任何有用的东西。 如果有人告诉我,我不得不在黄瓜故事和RSpec模型规格之间做出选择,我会每次都拿黄瓜的故事。 (幸运的是,我不必选择:)) – 2012-01-09 16:11:03