如何断言Rails集成测试中没有路由匹配?

我有一个Rails 3集成测试,测试我的路线。 它包含以下测试:

assert_routing( "/#{@category.url.path}/#{@foo.url.path}", { :controller => 'foo', :action => 'show', :category => @category.to_param, :foo => @foo.to_param } ) 

我还想测试一个没有路由匹配的情况。 显然,测试生成在这种情况下没有意义,所以我只需要assert_recognizes的反转。 我希望能够做到这样的事情:

 assert_not_recognized('/adfhkljkdhasjklhjkldfahsjkhdf') 

任何想法,缺少在assert_raises块中包装assert_recognize(实际上并不是那么可怕,现在我想到了它)?

通过在UrlGenerationErrorexception上断言,有类似的方法在Rails 4中进行检查:

 def test_no_routes_match_when_neither_foo_nor_bar_exist assert_raises(ActionController::UrlGenerationError) do get '/category/this-is-neither-a-foo-nor-a-bar' end end 

我最终这样做了:

  def test_no_routes_match_when_neither_foo_nor_bar_exist assert_raises(ActionController::RoutingError) do assert_recognizes({}, '/category/this-is-neither-a-foo-nor-a-bar') end end 

有点傻,但它完成了工作。

请注意,这不适用于Rails 4. 请参阅下面的答案以获取Rails 4解决方案。

通过调用#recognize_path你不会收到错误 。 相反,你会得到一个错误,但后来你找到了你正在寻找的线索。

 test "No routes match when neither_foo_nor_ bar exist" do begin assert_not(Rails.application.routes.recognize_path( 'category/this-is-neither-a-foo-nor-a-bar')) rescue ActionController::RoutingError => error assert error.message.start_with? "No route matches" end end 

你试过method_missing(selector, *args, &block)吗? 在这里定义