如何使用rspec测试命名路由?

13

假设我有一个命名路由:

map.some_route '/some_routes/:id', :controller => 'some', :action => 'other'

我该如何使用路由规范文件'spec/routing/some_routing_spec.rb'来测试命名路由?

在“describe SomeRouteController”块之后,我尝试过以下代码,但不起作用。我得到了 'undefined method "helper":

describe SomeRouteHelper, 'some routes named routes' do
  it 'should recognize some_route' do
    helper.some_route_path(23).should == '/some_routes/23'
  end
end
5个回答

13
如果这是在控制器规范(controller spec)中,你可以直接调用路由方法,不需要帮助程序。
describe SomeController do
  it 'should recognize ma routes!' do
   thing_path(23).should == '/things/23'
  end
end

1
谢谢,我也尝试过了,只是想听别人说我不是疯了,呵呵...结果发现我使用了嵌套资源,这需要使用parent_child_path(23)格式,而不是child_path(23)格式。 - btelles
RSpec 中的事情变化很快 - dchelimsky 建议使用 route_to 匹配器:route_to 匹配器指定请求(动词 + URI)是可路由的。当指定标准 RESTful 路由以外的路由时,它最有价值。https://www.relishapp.com/rspec/rspec-rails/v/2-4/docs/routing-specs/route-to-matcher(另请参见 Scarver 对此问题的回答) - notapatch

12
在RSpec-Rails 2.7+中,你可以创建一个spec/routing目录,并将你的路由规范放在里面。更多信息请参阅rspec-rails文档

6

2
您可以在控制器规范中使用assert_routing方法来完成此操作,如下所示:
describe UsersController do
  it "should recognize a specific users#show route" do
    assert_routing("/users/23", {:controller => "users", :action => "show", :id => 23})
  end
end

More documentation is here.


是的,那是用于常规路由识别的,但我正在寻找命名路由规范。不过还是谢谢! - btelles

1
这是我使用RSpec2、Shoulda和Capybara编写规格说明的方式。您可以将此示例文件保存在#{Rails.root}/spec/routing/thingz_routing_spec.rb或者我的首选#{Rails.root}/spec/routing/thingz_controller_spec.rb中。
require "spec_helper"

describe ThingzController do
  describe "routing" do
    it "routes to #index" do
      get("/thingz").should route_to("thingz#index")
    end
  end
end

备选语法:应该路由(:get, '/thingz').到(controller: 'thingz', action: 'index') - scarver2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接