Ruby on rails Rails助手不在测试环境中工作
我遵循了网站上提供的教程 它允许您通过覆盖帮助文件中的url_for方法,将子域选项传递给路由。 我发现帮助器方法如下所示:Ruby on rails Rails助手不在测试环境中工作,ruby-on-rails,ruby,cucumber,integration-testing,helper,Ruby On Rails,Ruby,Cucumber,Integration Testing,Helper,我遵循了网站上提供的教程 它允许您通过覆盖帮助文件中的url_for方法,将子域选项传递给路由。 我发现帮助器方法如下所示: module UrlHelper def with_subdomain(subdomain) subdomain = (subdomain || "") subdomain += "." unless subdomain.empty? [subdomain, request.domain, request.port_string].join
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
因此:
生成url:
"http://cats.example.com/sites/1/homepage"
这在开发中效果很好。但是,在我的Cumber测试中,使用:
sites_homepage_url(:subdomain => "cats")
产生:
"http://www.example.com/sites/1/homepage?subdomain=cats"
这表明我在帮助器中为添加到url_的功能不起作用。有人有什么想法吗
编辑:格式化并添加UrlHelper的代码。您可以尝试在集成测试中添加以下代码
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\u view/helpers/url\u helper.rb
(如果您使用的是从lib
文件夹自动加载),或者,您需要在config/application.rb
中明确要求该文件,因为其他解决方案不起作用,您可以尝试更难的解决方案
在初始值设定项文件(如config/initializers/url\u 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
请格式化问题中的代码。您需要将该模块包含在测试文件的顶部。例如,
如果文件位于/lib/url\u helper.rb
位置UrlHelper是在app/helpers/url\u helper.rb中定义的,则包含UrlHelper
,但是当我显式地包含它时,我会得到相同的行为。看起来我在测试中对url\u的定义写得太多了,但没有在开发中。进一步检查后(我让一个朋友和我一起看了看)我们发现ActionView::TestCase需要ActionView::Helpers::UrlHelper来覆盖我的url\u。关于如何确保我的模块是加载的最后一个版本,有什么想法吗?这对问题没有任何影响。如上所述,从ActionView::TestCase中包含该模块是编写我的url\u版本的过度之处。
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