4

我正在尝试polymorphic_path在 Rails 3 的功能测试中使用。

起初我会得到

NoMethodError: undefined method `polymorphic_path' for #<ArticlesControllerTest:0x492f17c>

然后我添加了

include Rails.application.routes.url_helpers

undefined method error停止但现在是常规路径,article_path(article)例如停止工作:

NameError: undefined local variable or method `default_url_options' for #<ArticlesControllerTest:0x33ccbe0>
.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.0.9/lib/action_dispatch/testing/assertions/routing.rb:175:in `method_missing'
.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.0.9/lib/action_dispatch/routing/url_for.rb:102:in `url_options'
.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.0.9/lib/action_dispatch/routing/url_for.rb:131:in `url_for'
.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.0.9/lib/action_dispatch/routing/route_set.rb:195:in `article_path'

我曾经能够通过包含在 Rails 2 中正常使用 polymorphic_path

include ActionController::UrlWriter

我怎样才能让它在 Rails 3 中工作?

4

3 回答 3

6

我需要包括:

include ActionDispatch::Routing::UrlFor
include Rails.application.routes.url_helpers

并设置:

default_url_options[:host] = 'www.example.com'

我通过这篇文章发现回答了类似的问题 http://steve.dynedge.co.uk/2010/04/29/rails-3-rake-and-url_for/

于 2011-08-11T03:22:39.753 回答
0

我在重构一些 Rails4 测试以使其与模型无关时遇到了这个问题。我找到

something_path(obj)

工作但

polymorphic_path(obj)

没有。上述建议也没有对我有用。我确实发现这样做了,但是:

@controller.polymorphic_path(obj)

这是在self是 的后代的上下文中ActionController::TestCase

解决这个问题的另一种方法是在控制器测试类中定义一个委托方法:

def polymorphic_path(*args) 
  @controller.polymorphic_path(*args)
end
于 2016-05-06T14:42:17.483 回答
-1

你有没有尝试过:

Rails.application.routes.url_helpers.polymorphic_path

? :)

于 2011-08-10T09:42:57.260 回答