【问题标题】:How to use rspec to test named routes?如何使用 rspec 测试命名路由?
【发布时间】:2010-12-18 08:59:21
【问题描述】:

鉴于我有一条命名路线:

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

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

我在“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

【问题讨论】:

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


    【解决方案1】:

    这就是我使用 RSpec2、Shouda 和 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
    

    【讨论】:

    • 替代语法:should route(:get, '/thingz').to(controller: 'thingz', action: 'index')
    【解决方案2】:

    也有一个不错的匹配器:

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

    更多关于在 rspec 中使用 shoulda 匹配器的信息:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 谢谢,我也试过了,就是想听听别人说我没疯,呵呵...原来我用的是嵌套资源,需要parent_child_path(23)格式为反对 child_path(23) 格式。
        • RSpec 中的变化很快 - dchelimsky 建议使用 route_to 匹配器: route_to 匹配器指定请求(动词 + uri)是可路由的。在指定标准 RESTful 路由以外的路由时,它最有价值。 relishapp.com/rspec/rspec-rails/v/2-4/docs/routing-specs/…(另见 Scarver 对此问题的回答)
        【解决方案5】:

        您可以在控制器规范中使用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

        【讨论】:

        • 是的,这是用于常规路线识别的,不过我一直在寻找命名路线规范。不过谢谢!
        猜你喜欢
        • 2011-04-20
        • 1970-01-01
        • 2011-08-21
        • 2011-08-04
        • 1970-01-01
        • 2012-02-12
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多