在Rails 3中使用Cucumber / Capybara,如何设置自定义User-Agent字符串?

时间:2010-08-03 17:44:31

标签: ruby-on-rails http testing cucumber capybara

在我的Rails 3应用程序中,我对iPhone和桌面浏览器有不同的布局。我正在尝试使用Cucumber / Capybara测试iPhone布局。到目前为止,我在请求的HTTP标头中设置iPhone User-Agent字符串的所有尝试都失败了。

我已经按照Testing custom headers and ssl with Cucumber and Capybara教程进行操作,但似乎没有在HTTP请求中设置User-Agent字符串。

如果我只是使用iPhone浏览我的Rails应用程序,我会得到正确的布局。我正在使用Rack-Mobile-Detect将Rails request.format设置为:iphone。

有关如何使这项工作的任何想法?我准备放弃Capybara并回到Webrat。

这是我到目前为止所拥有的:

Feature: Detect Browser
  In order to have different layouts for iPhone vs. desktop browsers
  As a developer
  I want to show different layouts for different browsers

Scenario: Show home page with desktop layout 
  Given I am using "a desktop browser"
  When I go to "the home page"
  Then I should see "desktop browser"

Scenario: Show home page with iPhone layout
  Given I am using "mobile safari"
  When I go to "the home page"
  Then show me the page
  Then I should see "mobile safari"

Detect_browser_steps.rb

Given /^(?:|I )am using (.+)$/ do |browser|
  case browser
  when "mobile safari"
    agent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7D11 Safari/528.16"
    add_headers({'User-Agent' => agent})
  else
    # don't set a special User-Agent header
  end
end

headers_hack.rb

# http://aflatter.de/2010/06/testing-headers-and-ssl-with-cucumber-and-capybara/
# The following solution will work only if you use the :rack_test driver.
module RackTestMixin

  def self.included(mod)
    mod.class_eval do
      # This is where we save additional entries.
      def hacked_env
        @hacked_env ||= {}
      end

      # Alias the original method for further use.
      alias_method  :original_env, :env

      # Override the method to merge additional headers.
      # Plus this implicitly makes it public.
      def env
        original_env.merge(hacked_env)
      end
    end
  end

end

Capybara::Driver::RackTest.send :include, RackTestMixin

module HeadersHackHelper

  def add_headers(headers)
    page.driver.hacked_env.merge!(headers)
  end

end

World(HeadersHackHelper)

2 个答案:

答案 0 :(得分:6)

不得不对此进行一些调整,但最后我设法通过添加以下内容来实现:

# features/support/capybara_headers.rb:

module CapybaraHeadersHelper
  def add_headers(headers)
    headers.each do |name, value|
      page.driver.browser.header(name, value)
    end
  end
end
World(CapybaraHeadersHelper)

你可以在我写的blog post中获得更多信息,但基本上就是这样。

答案 1 :(得分:1)

嘿那里。很高兴你找到了我的帖子; - )

您是否检查Rack::Test是否将标头传递给控制器​​? 您可以在控制器中尝试Rails.logger.info("Headers: #{headers.inspect}")之类的内容,然后检查日志文件。