簡體   English   中英

Rails 助手不在測試環境中工作

[英]Rails helpers not working in test environment

我遵循了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" 

這在開發中運行良好。 然而,在我的 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

您可以嘗試在集成測試中添加以下代碼

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中明確地要求該文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM