How to test mount rack app in rails3

原创文章,转载请注明来源并保留原文链接

在测试路由的时候,可以通过:

class RouteTest < ActionController::TestCase
  assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
end

我们也知道:

route = Dummy::Application.routes
route.recognize_path "/posts/1"
#=> { :controller => "posts", :action => "show", :id => "1" }

route.generate :controller => "posts", :action => "show", :id => "1"
#=> "/posts/1"

但是对于下面这种情况:

My::Application.routes.draw do
  mount Rack::App => "/rack"
end

通过route是找不到的

route = My::Application.routes
route.recognize_path "/rack"
#=> "No route matches /rack"

如何测试呢?现提供下面这个方法:

routes = Dummy::Application.routes.routes
server = routes.select { |r| r.app.instance_of?(Rack::App) }.pop
# test mount successful
assert !server.nil?
path   = server.path.spec.to_s
# test mount path correct
assert_equal('/rack', path)

注意:上面的测试只是覆盖了Rack App是否挂载在正确的路径上,而不会测试返回的内容是否正确!

Leave a Reply

Your email address will not be published. Required fields are marked *