gpt4 book ai didi

ruby-on-rails-3 - Rails、Capybara 和子域 : how to visit certain subdomain

转载 作者:行者123 更新时间:2023-12-03 22:00:30 26 4
gpt4 key购买 nike

Rails 3、Cucumber 0.9.4、Capybara 0.4.0

我想用子域测试我的功能。我找到了解决方案:

Given /^I visit subdomain "(.+)"$/ do |sub|
Capybara.default_host = "#{sub}.example.com" #for Rack::Test
Capybara.app_host = "http://#{sub}.example.com:9887" if Capybara.current_driver == :culerity
end

如果我运行 cucumber features/subdomain.feature,它会起作用但如果我运行 cucumber features 就会失败!这令人难以置信,但这是真的。我记录了当前的网址,它是 subdomain.example.comcucumber features/subdomain.featurewww.example.comcucumber features对于一个场景
Scenario: subdomain scenario
Given I visit subdomain "subdomain"

在这两种情况下!

我不知道原因...

是否有使用 capybara 测试子域的最佳方法?

最佳答案

好的,这应该是一个相当简单易懂的 Capybara hack,它产生了所需的行为,即每次切换子域时都能够创建一个新 session 。这对于用户在一个域上注册(这会为其帐户创建一个子域)然后最终需要导航到该子域的站点非常有用。

首先(这部分对于其他解决方案来说相当常见)继续并给自己一种在 Cucumber 步骤中更改 Capybara.default_host 的方法。我是这样做的:

Then /^I switch the subdomain to (\w+)$/ do |s|
Capybara.default_host = "#{s}.smackaho.st"
end

在您希望使用新子域的地方将此步骤插入到您的 Cucumber 功能中。例如:
When I open the email
Then I should see "http://acme.rightbonus.com/users/confirmation" in the email body

Given I switch the subdomain to acme
When I follow "Click here to finish setting up your account" in the email
Then I should be on the user confirmation page for acme

现在是神奇的monkeypatching,使这项工作。基本上,您希望 Capybara 足够智能以检测子域何时更改并重置其 RackTest session 对象。
# features/support/capybara.rb

class Capybara::Driver::RackTest
# keep track of the default host you started with
def initialize(app)
raise ArgumentError,
"rack-test requires a rack application, but none was given" unless app
@app = app
@default_host = Capybara.default_host
end

def process(method, path, attributes = {})
reset_if_host_has_changed
path = ["http://", @default_host, path].join
return if path.gsub(/^#{request_path}/, '') =~ /^#/
path = request_path + path if path =~ /^\?/
send(method, to_binary(path), to_binary( attributes ), env)
follow_redirects!
end

private

def build_rack_mock_session # :nodoc:
puts "building a new Rack::MockSession for " + Capybara.default_host
Rack::MockSession.new(app, Capybara.default_host || "www.example.com")
end

def reset_if_host_has_changed
if @default_host != Capybara.default_host
reset! # clears the existing MockSession
@default_host = Capybara.default_host
end
end
end

此补丁适用于 Capybara 0.4.1.1,除非修改,否则可能不适用于不同版本。祝你好运。

关于ruby-on-rails-3 - Rails、Capybara 和子域 : how to visit certain subdomain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4217927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com