Testing subdomains in capybara / rspec

Currently, I am almost completing a long way in testing rails, but I hit my head on how to get query specifications that work with subdomains.

In development, I use pow with URLs such as:, http://teddanson.myapp.dev/accountwhich is all fine and dandy.

In testing, I let capybara do this, which returns localhost http://127.0.0.1:50568/account, which obviously does not play well with the entire subdomains. It works great for the public part of the application, which does not require subdomains, but how to access the user’s subdomain account outside of me.

Access to the appropriate routes is carried out using the following methods:

class Public
  def self.matches?(request)
    request.subdomain.blank? || request.subdomain == 'www'
  end
end

class Accounts
  def self.matches?(request)
    request.subdomain.present? && request.subdomain != 'www'
  end
end

, , , - - , , , . !

+5
2

, capybara, . , .

class SubdomainResolver
  class << self
    # Returns the current subdomain
    def current_subdomain_from(request)
      if Rails.env.test? and request.params[:_subdomain].present?
        request.params[:_subdomain]
      else
        request.subdomain
      end
    end
  end
end

, test, _subdomain, , _subdomain request.subdomain ( ).

, url, app/helpers :

module UrlHelper
  def url_for(options = nil)
    if cannot_use_subdomain?
      if options.kind_of?(Hash) && options.has_key?(:subdomain)
        options[:_subdomain] = options[:subdomain]
      end
    end

    super(options)
  end

  # Simple workaround for integration tests.
  # On test environment (host: 127.0.0.1) store current subdomain in the request param :_subdomain.
  def default_url_options(options = {})
    if cannot_use_subdomain?
      { _subdomain: current_subdomain }
    else
      {}
    end
  end

  private

  # Returns true when subdomains cannot be used.
  # For example when the application is running in selenium/webkit test mode.
  def cannot_use_subdomain?
    (Rails.env.test? or Rails.env.development?) and request.host ==  '127.0.0.1'
  end
end

SubdomainResolver.current_subdomain_from config/routes.rb

, .

+1

All Articles