简体   繁体   English

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

[英]How to use rspec to test named routes?

Given I have a named route: 鉴于我有一个命名的路线:

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

How do I use the routing spec file 'spec/routing/some_routing_spec.rb' to test for that named route? 如何使用路由规范文件'spec / routing / some_routing_spec.rb'测试该命名路由?

I've tried this after the "describe SomeRouteController" block and it doesn't work, I get 'undefined method "helper": 我在“ describe SomeRouteController”块之后尝试了此操作,但它不起作用,我得到了“未定义的方法” 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

If this is in a controller spec, you can call the routing method directly, no helper needed. 如果这在控制器规格中,则可以直接调用路由方法,而无需帮助程序。

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

In RSpec-Rails 2.7+ you can create a spec/routing directory and put your routing specs in there. 在RSpec-Rails 2.7+中,您可以创建一个spec/routing目录,并将路由规范放在该目录中。 See the rspec-rails docs for more info. 有关更多信息,请参见rspec-rails文档

there's a nice shoulda matcher for this too: 也有一个不错的相配者:

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

more information on using shoulda matchers with rspec: 有关将rda匹配器与rspec一起使用的更多信息:

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

You can do this in your controller specs with the assert_routing method, like so: 您可以使用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 . 更多文档在这里

This is how I write the specs using RSpec2, Shoulda, and Capybara. 这就是我使用RSpec2,Shoulda和Capybara编写规格的方式。 You would save this example file in #{Rails.root}/spec/routing/thingz_routing_spec.rb or my preference #{Rails.root}/spec/routing/thingz_controller_spec.rb 您可以将此示例文件保存在#{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

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

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