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
so:
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 的功能不起作用。有人有什么想法吗?
编辑:格式化并添加 UrlHelper 的代码。
I've followed the tutorial available at http://railscasts.com/episodes/221-subdomains-in-rails-3.
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
so:
sites_homepage_url(:subdomain => "cats")
produces the url:
"http://cats.example.com/sites/1/homepage"
This works fine in development. In my cucumber tests, however, using:
sites_homepage_url(:subdomain => "cats")
produces:
"http://www.example.com/sites/1/homepage?subdomain=cats"
which indicates the functionality I added to url_for in the helper isn't working. Anyone got any ideas?
Edit: Formatting and added the code for the UrlHelper.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于其他解决方案均无效,您可以尝试更难的解决方案。
在初始化文件(例如 config/initializers/url_for_patch.rb)中,添加以下内容:
As the other solutions have not worked, you can try a harder one.
In an initializer file (like config/initializers/url_for_patch.rb), add this:
您可以尝试在集成测试中添加以下代码
You can try add below code in your integration testing
您问题中的代码正在顶级命名空间中定义一个新的
UrlHelper
模块。如果您尝试重写ActionView::Helpers::UrlHelper
中的方法,则需要完全限定该模块:我不确定 Rails 是否对此完全满意 app/帮助程序,因此您可能需要将其放入
lib/action_view/helpers/url_helper.rb
中(如果您使用从lib
文件夹自动加载),否则您将需要明确要求您的 config/application.rb 中的文件The code in your question is defining a new
UrlHelper
module in the top-level namespace. If you're trying to override methods inActionView::Helpers::UrlHelper
, you'll need to fully qualify the module:I'm not sure if Rails will be entirely happy with that in app/helpers, so you might need to put this in
lib/action_view/helpers/url_helper.rb
(if you're using autoloading from thelib
folder), or you'll need to explicitly require the file in yourconfig/application.rb