biagidp
biagidp

Reputation: 2185

Rails helpers not working in test environment

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.

Upvotes: 3

Views: 2258

Answers (3)

Maurício Linhares
Maurício Linhares

Reputation: 40333

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

Upvotes: 2

Jacob
Jacob

Reputation: 23225

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

Upvotes: 0

gnepud
gnepud

Reputation: 23

You can try add below code in your integration testing

include ActionView::Helpers::UrlHelper

Upvotes: 0

Related Questions