Rails助手不在测试环境中工作

我已经按照http://railscasts.com/episodes/221-subdomains-in-rails-3上的教程进行了操作。

它允许您通过覆盖帮助文件中的url_for方法将子域选项传递给路由。 我的帮手方法看起来像这样:

module UrlHelper def with_subdomain(subdomain) subdomain = (subdomain || "") subdomain += "." unless subdomain.empty? [subdomain, request.domain, request.port_string].join end def url_for(options = nil) if options.kind_of?(Hash) && options.has_key?(:subdomain) options[:host] = with_subdomain(options.delete(:subdomain)) end super end end 

所以:

 sites_homepage_url(:subdomain => "cats") 

生成url:

 "http://cats.example.com/sites/1/homepage" 

这在开发中工作得很好。 然而,在我的黄瓜测试中,使用:

 sites_homepage_url(:subdomain => "cats") 

生产:

 "http://www.example.com/sites/1/homepage?subdomain=cats" 

这表示我在助手中添加到url_for的function不起作用。 有人有任何想法吗?

编辑:格式化并添加UrlHelper的代码。

由于其他解决方案没有奏效,您可以尝试更难的解决方案。

在初始化文件(如config / initializers / url_for_patch.rb )中,添加以下内容:

 ActionView::Helpers::UrlHelper.class_eval do def with_subdomain(subdomain) subdomain = (subdomain || "") subdomain += "." unless subdomain.empty? [subdomain, request.domain, request.port_string].join end alias_method_chain :url_for, :subdomain def url_for_with_subdomain(options = nil) if options.kind_of?(Hash) && options.has_key?(:subdomain) options[:host] = with_subdomain(options.delete(:subdomain)) end url_for_without_subdomain( options ) end end 

您可以尝试在集成测试中添加以下代码

 include ActionView::Helpers::UrlHelper 

您的问题中的代码是在顶级命名空间中定义新的UrlHelper模块。 如果您尝试覆盖ActionView::Helpers::UrlHelper ,则需要完全限定模块:

 module ActionView module Helpers module UrlHelper def url_for # override as in your question end end end end 

我不确定Rails是否会对app / helpers中的内容感到满意,所以你可能需要把它放在lib/action_view/helpers/url_helper.rb (如果你是从lib文件夹中使用自动加载),或者你’我需要在config/application.rb明确要求该文件