在我的Rails 3應用程序中,我對iPhone和桌面瀏覽器有不同的佈局。我正在嘗試使用Cucumber/Capybara測試iPhone佈局。到目前爲止,我所有在請求的HTTP頭中設置iPhone用戶代理字符串的嘗試都失敗了。在Rails 3中使用Cucumber/Capybara,如何設置自定義的User-Agent字符串?
我遵循Testing custom headers and ssl with Cucumber and Capybara教程,但它似乎沒有在HTTP請求中設置User-Agent字符串。
如果我只是使用我的iPhone瀏覽我的Rails應用程序,我會得到正確的佈局。我正在使用Rack-Mobile-Detect將Rails request.format設置爲:iphone。
關於如何使這項工作的任何想法?我準備把水豚甩開,然後回到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)
很簡單。謝謝! – 2012-03-04 23:32:21