不幸的是,你不能在 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
我希望它会帮助你。