在capybara/rspec中测试子域名

5
我目前已经接近完成对Rails测试的长期探索,但我在如何使用子域名进行请求测试方面遇到了困难。
在开发中,我使用像这样的URL: http://teddanson.myapp.dev/account ,这一切都很好。
在测试中,我让Capybara自己处理,它返回本地主机地址: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

我感觉自己像是疯了一样,如果有人能提供任何建议或建议来帮助我,那将非常非常棒。谢谢你的帮助!

2个回答

2

使用37signals xip.io的详细而优雅的解决方案。谢谢!@cmaitchison - BenU
在原始文章中,作者使用了xip.io。但这意味着这些测试需要互联网连接,否则它们将失败!而且这也会减慢测试套件的速度,因为每个子域名的测试都会首先进入该网站。 - ExiRe
答案中提到的链接已经失效。 - navraj

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

正如您所见,当应用程序在测试模式下运行并设置了特殊的_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 中作为约束条件使用。

希望这能对您有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接