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

时间:2009-11-19 16:02:39

标签: ruby-on-rails ruby routing rspec routes

鉴于我有一条命名路线:

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

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

我在“描述SomeRouteController”块之后尝试了这个并且它不起作用,我得到'未定义的方法'帮助器“:

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 个答案:

答案 0 :(得分:13)

如果这是在控制器规范中,您可以直接调用路由方法,不需要帮助程序。

describe SomeController do
  it 'should recognize ma routes!' do
   thing_path(23).should == '/things/23'
  end
end

答案 1 :(得分:12)

在RSpec-Rails 2.7+中,您可以创建一个spec/routing目录并将路由规范放在那里。有关详细信息,请参阅rspec-rails docs

答案 2 :(得分:6)

这也是一个很好的应该匹配的问题:

it { should route(:get, "/users/23").to(:action => "show", :id => 23)

有关使用带有rspec的shoulda匹配器的更多信息:

https://github.com/thoughtbot/shoulda-matchers

答案 3 :(得分: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

更多文档是here

答案 4 :(得分: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