我已按照 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")
生成网址:
"http://cats.example.com/sites/1/homepage"
这在开发中运行良好。然而,在我的 cucumber 测试中,使用:
sites_homepage_url(:subdomain => "cats")
产生:
"http://www.example.com/sites/1/homepage?subdomain=cats"
这表示我在帮助程序中添加到 url_for 的功能不起作用。有人有什么想法吗?
编辑:格式化并添加了 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
关于ruby-on-rails - Rails 助手不在测试环境中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6721952/