使用Cucumber/Capybara时出现子域名问题

3
我已经成功地为我的应用程序添加了使用动态子域名的功能。但问题在于,当我运行Cucumber测试时,当我的应用程序执行包含子域名的redirect_to时,我会收到以下错误提示:
features/step_definitions/web_steps.rb:27
the scheme http does not accept registry part: test_url.example.com (or bad hostname?)

我有一个注册控制器动作,它创建用户和所选择的帐户,并将用户重定向到注销方法,并根据用户在注册表单中选择的子域指定子域。以下是用户和帐户模型创建并保存后发生的重定向操作的代码:

redirect_to :controller => "sessions", :action => "destroy", :subdomain => @account.site_address

以下是我的Rails 3路由:

constraints(Subdomain) do
  resources :sessions
  match 'login', :to => 'sessions#new', :as => :login
  match 'logout', :to => 'sessions#destroy', :as => :logout
  match '/' => 'accounts#show'
end

以下是我为子域类编写的代码,它符合上述约束条件:

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

我在ApplicationController中添加了UrlHelper:

class ApplicationController < ActionController::Base
  include UrlHelper
  protect_from_forgery
end

这是上述UrlHelper类的代码:
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

以上所有代码允许我在本地浏览器中正常运行子域名。但是当我运行Cucumber测试时,出现了上述问题。测试会点击注册按钮,然后调用redirect_to并抛出上述异常。

这是我的gem文件的内容:

require 'subdomain'

SomeApp::Application.routes.draw do

  resources :accounts, :only => [:new, :create]
  match 'signup', :to => 'accounts#new'

  constraints(Subdomain) do
    resources :sessions
    match 'login', :to => 'sessions#new', :as => :login
    match 'logout', :to => 'sessions#destroy', :as => :logout

    match '/' => 'accounts#show'
  end
end

请问是否有其他方法可以让我的测试现在能够正常工作?我想要的是修复方法或者一种不使用子域名进行测试的方法(例如模拟检索账户名称的方法)。


为了避免这个错误,我改变了url_for方法,进行了检查以确保我不在测试环境中。这让我避开了错误,但它并没有模拟“生产”所做的事情。这将强制我使用不同的方法来检索当前帐户名称,而不是从子域中获取。 - Jamie Wright
1个回答

1

我在我的代码中也有同样的模式。我使用Capybara(但不是Cucumber),我能够像这样解决它:

    # user creates an account that will have a new subdomain
    click_button "Get Started"  
    host! "testyco.myapp.com"

    # user is now visiting app on new subdomain
    visit "/register/get_started/" + Resetkey.first.resetkey
    assert_contain("Get Started Guide")

host! 命令有效地更改了应用程序从测试请求中看到的主机。

编辑:刚意识到这在 webrat 中可以工作,但在 capybara 中不行(我现在同时使用两者,逐步淘汰 webrat)。在 capybara 中我这样做要么是点击链接到新域名(capybara 会跟随它),要么是:

 visit "http://testyco.myapp.com/register"

编辑:另一个更新。找到了一种方法,可以在每个事件中不必使用完整的URL。

        host! "test.hiringthing.com"
        Capybara.app_host = "http://test.hiringthing.com"

在测试设置中。

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