Rails console 中测试路由规则的问题?

piginzoo · 2012年02月15日 · 最后由 piginzoo 回复于 2012年02月15日 · 3397 次阅读

在 Rails 3.1 中,想在 rails console 里测试一下路由规则,于是输入

r = Rails.application.routes
r.recognize_path "/"

结果报 Rack 的错误,看了一下 rack 的代码,晕, 遇到过的兄弟帮忙看看啥原因?

irb(main):002:0> r = Rails.application.routes
irb(main):002:0> r.recognize_path "/"
RuntimeError: route set not finalized
        from C:/software/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/rack-mount-0.8.3/lib/rack/mount/route_set.rb:81:in `recognize'
        from C:/software/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/actionpack-3.1.1/lib/action_dispatch/routing/route_set.rb:546:in `recognize_path'
        from (irb):2
        from C:/software/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/railties-3.1.1/lib/rails/commands/console.rb:45:in `start'
        from C:/software/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/railties-3.1.1/lib/rails/commands/console.rb:8:in `start'
        from C:/software/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/railties-3.1.1/lib/rails/commands.rb:40:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'
irb(main):003:0>

我推荐使用直接在项目根目录执行:rake routes

C:/software/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/rack-mount-0.8.3/lib/rack/mount/route_set.rb:81:in `recognize'

def recognize(obj) raise 'route set not finalized' unless @recognition_graph

说是@recognition_graph未被初始化

继续排查到 rehash 中初始化了,可是谁调用 rehash,不得知 def rehash #:nodoc: Utils.debug "rehashing" @recognition_keys = build_recognition_keys

@recognition_graph = build_recognition_graph

module Rack::Mount class RouteSet def initialize(options = {}, &block) if block_given? yield self rehash <=====================这里调用了 end

end

可是,我如何能在 console 中传入一个 block 呢,于是乎越想越糊涂,

得,有经验的说说,你们如何在测试路由呢,除了写单元测试外啊,有什么比较快姐的方式。

ruby-1.9.2-p180 :014 > Rails.application.routes.finalize! =>
ruby-1.9.2-p180 :015 > Rails.application.routes.recognize_path("/users", :method => :get) Creating scope :public. Overwriting existing method Link.public. Creating scope :private. Overwriting existing method Link.private. Creating scope :protected. Overwriting existing method Link.protected. => {:controller=>"links", :action=>"redirect", :id=>"users"}

手动 finalize! 一下试试...

#2 楼 @piginzoo 如何理解你说的测试路由?你只用 check 路由是否正确生成...rake routes 即可... 至于生成的对不对,是 Rails 会有测试来保证...应用层不用关心上一层生成的路由对不对...

果然奏效,谢了!

rake routes 是可以的,我就是想随时时刻的方便看看某个 URL 被解析成啥 controller&action。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号