2012-09-05 41 views
0

對於檢測和響應移動用戶代理,我使用的測試。移動與水豚MIME格式/ rspec的

Mime::Type.register_alias "text/html", :mobile 

和方法我想知道什麼是與水豚測試的最佳方法。這篇文章建議設立一個iphone驅動程序Capybara.register_driver :iphone do |app|

http://blog.plataformatec.com.br/2011/03/configuring-user-agents-with-capybara-selenium-webdriver/

但我想在那裏MIME類型是通過URL擴展

localhost/index.mobile 

設置更靈活的方式,並在那裏我可以做這

visit user_path(format: :mobile) 

Rails的理解延伸,並設置formatparams散列,但我如何獲得URL助手方法將其作爲文件擴展名添加到所有網址?

+0

答案就在這裏 - http://railscasts.com/episodes/199-mobile-devices所以我會回答我自己的問題。 –

回答

1

我的答案是堅持在這個Railscast會話變量的格式:http://railscasts.com/episodes/199-mobile-devices。我選擇使用URL擴展而不是查詢字符串參數,因爲它看起來更好。

這是我在application_controller.rb代碼:

def mobile_device? 
    session.has_key?(:mobile) ? session[:mobile] : request.user_agent =~ /Mobile|webOS/ 
end 
helper_method :mobile_device? 

def prepare_for_mobile 
    # avoid messing with .json, .xml 
    if request.format == 'text/html' 
    # only do this when an explicit extension is present 
    case File.extname(URI.parse(request.fullpath).path) 
    when '.html' 
     session[:mobile] = false 
    when '.mobile' 
     session[:mobile] = true 
    end 
    # stop using a session param and go back to letting the user_agent decide 
    when '.ua' 
     session.delete(:mobile) 
    end 
    request.format = mobile_device? ? :mobile : :html 
    end 
end 

,這裏是mime_types.rb

Mime::Type.register_alias "text/html", :ua  # let the user agent decide 
Mime::Type.register_alias "text/html", :mobile # mobile