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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Rails 3中使用Cucumber / Capybara,如何设置自定义User-Agent字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的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)

解决方法

不得不对此进行一些调整,但最终我设法通过添加
# 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中获得更多信息,但基本上就是这样.

猜你在找的Ruby相关文章