How to test mobile devices and mobile mime types

Hi All,

I just started incorporating a mobile MIME format into my websites to account for mobile phone technologies visiting my pages. I decided to share a functional controller test for requesting the mobile mime type and asserting if it finds a particular div selector.

This test case can be applied to Ryan Bates' screencast on mobile devices:

To make things easier, I've posted the entire test case here:

The main test is:

# When requesting mobile you can set the request environment two ways # @request.env['HTTP_ACCEPT'] = "mobile" # OR # @request.accept = "mobile" require 'test_helper'

class HomeControllerTest < ActionController::TestCase   test "should get mobile index" do     @request.accept = "mobile"     get :index     assert_response :success     assert_select "div[data-role=header]" do       assert_select 'h1', 'Your Header Title'     end   end end

In your config/initializers/mime_types.rb you would have:

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

And in your views/home/ you would have an ERB view for index.mobile.erb that contains something similar:

<div data-role="header">   <h1>Your Header Title</h1> </div>

I'm using JQMobile so the mobile divs are using a data-role identifier for header, content, footer, etc. Tailor this to your own needs. I hope this helps someone down the road.

Take care.

Adding an example for show.mobile.erb for a user model so that you don't encounter any gotchas. This is using the same example from above:

setup do   @user = users(:testuser) end

test "should get show.mobile.erb" do   @request.accept = "mobile"   get :show, :id => @user.to_param, :format => 'mobile'   assert_response :success   assert_select "div[data-role=header]" do     assert_select 'h1', 'Your Header Title'   end end

Make sure that when you test this statement:

get :show, :id => @user.to_param

.. that you add , :format => 'mobile'

.. or you will encounter a 406 error.

In addition, don't try to pass a symbol for :mobile in the get request or you will encounter the same 406 error.

Thanks.