5

我目前几乎即将结束 Rails 测试的漫长旅程,但我正在努力研究如何让请求规范与子域一起使用。

在开发中,我将 pow 与 url 一起使用,例如:http://teddanson.myapp.dev/account这一切都很好而且花花公子。

在测试中,我让 capybara 做它返回 localhost 的事情,http://127.0.0.1:50568/account这显然不能与整个子域的事情配合得很好。它适用于不需要子域的应用程序的公共部分,但是如何访问给定用户的子域帐户超出了我的范围。

通过以下方法访问相关路由:

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

我觉得我正在服用疯狂的药丸,所以如果有人有任何建议或建议可以帮助我,那将非常非常棒。谢谢你的帮助!

4

2 回答 2

2

您可以使用 xip.io 来测试 Capybara/RSpec 中的子域,如下所述:https ://web.archive.org/web/20171222062651/http://chrisaitchison.com/2013/03/17/testing-subdomains-在轨/

于 2013-03-17T21:47:25.870 回答
1

不幸的是,你不能在 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

我希望它会帮助你。

于 2012-08-31T09:04:44.717 回答