How to use polymorphic_path in a functional test in Rails 3

喜夏-厌秋 提交于 2019-12-10 15:54:25

问题


I'm trying to use polymorphic_path in a functional test in Rails 3.

At first I would get

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

And then I added

include Rails.application.routes.url_helpers

The undefined method error stopped, but now regular paths, like article_path(article) for example stopped working:

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'

I used to be able to use polymorphic_path normally in Rails 2 by including

include ActionController::UrlWriter

How can I get this to work in Rails 3?


回答1:


I need to include:

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

and set:

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

I found out via this post that answers a similar issue http://steve.dynedge.co.uk/2010/04/29/rails-3-rake-and-url_for/




回答2:


I encountered this problem when refactoring some Rails4 tests to make them model-agnostic. I found that

something_path(obj)

worked but

polymorphic_path(obj)

didnt. None of the above suggestions worked for me either. I did find that this did, however:

@controller.polymorphic_path(obj)

This is in the context where self is a descendent of ActionController::TestCase.

Another way to work around this is do define a delegation method in the controller test class:

def polymorphic_path(*args) 
  @controller.polymorphic_path(*args)
end



回答3:


Have you tried:

Rails.application.routes.url_helpers.polymorphic_path

? :)



来源:https://stackoverflow.com/questions/6999112/how-to-use-polymorphic-path-in-a-functional-test-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!