开发者

Rails helpers not working in test environment

开发者 https://www.devze.com 2023-03-21 07:01 出处:网络
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

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开发者_JS百科.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.


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:

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


You can try add below code in your integration testing

include ActionView::Helpers::UrlHelper


The code in your question is defining a new UrlHelper module in the top-level namespace. If you're trying to override methods in ActionView::Helpers::UrlHelper, you'll need to fully qualify the module:

module ActionView
  module Helpers
    module UrlHelper
      def url_for
        # override as in your question
      end
    end
  end
end

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 the lib folder), or you'll need to explicitly require the file in your config/application.rb

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号