Rails助手不能在测试环境中工作 [英] Rails helpers not working in test environment
问题描述
我已遵循 http://railscasts.com/上的教程episodes / 221-subdomains-in-rails-3 。
它允许您通过覆盖辅助程序中的url_for方法将子域选项传递到路由文件。
我的辅助方法如下所示:
It allows you to pass a subdomain option to your routes by overriding the url_for method in a helper file. I've helper method looks like this:
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"
这在开发中工作正常。然而,在我的黄瓜测试中,使用:
This works fine in development. In my cucumber tests, however, using:
sites_homepage_url(:subdomain => "cats")
产生:
"http://www.example.com/sites/1/homepage?subdomain=cats"
表示我添加到url_for在助手的功能不工作。任何人都有任何想法?
which indicates the functionality I added to url_for in the helper isn't working. Anyone got any ideas?
编辑:格式化并添加UrlHelper的代码。
Formatting and added the code for the UrlHelper.
推荐答案
因为其他解决方案没有工作,你可以尝试一个更难的。
As the other solutions have not worked, you can try a harder one.
在一个初始化文件(像 config / initializers / url_for_patch .rb ),请添加:
In an initializer file (like config/initializers/url_for_patch.rb), add this:
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
这篇关于Rails助手不能在测试环境中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!