我已经成功地在我的应用程序中添加了使用动态子域的功能。问题是,当我运行我的 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?)
我有一个注册 Controller 操作,它创建用户和所选帐户,并将用户重定向到注销方法,并根据用户在注册表单中选择的子域指定子域。以下是创建并保存用户和帐户模型后发生的重定向操作的代码:
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
我将 UrlHelper 添加到 ApplicationController:
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
能否请您告诉我另一种让我的测试现在正常工作的方法?我会对修复程序或无需使用子域即可测试我的方法的方法感兴趣(例如,检索帐户名称的模拟方法)。
最佳答案
我的代码中有同样的模式。我使用 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")
楼主!命令有效地更改主机,因为它在测试请求中显示给应用程序。
编辑:刚刚意识到这是与 webrat 一起工作,但不是 capybara(我正在使用两者,现在逐步淘汰 webrat。)我在 capybara 中这样做的方式是单击指向新域的链接(capybara跟随它)或:
visit "http://testyco.myapp.com/register"
编辑:另一个更新。找到了一种无需在每个事件中都使用完整 URL 即可工作的方法。
host! "test.hiringthing.com"
Capybara.app_host = "http://test.hiringthing.com"
在测试设置中。
关于ruby-on-rails - 在 Cucumber/Capybara 中使用子域的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4029527/