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 B.’ screencast on mobile

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”


@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’

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
that contains something similar:

Your Header Title

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.

Edit: Also, if someone wants to post similar tests for Rspec or other,
relating to the same topic, please feel free to do so.

Adding an example for 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)

test “should get” 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’

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.

Edit: You can actually add :format => :mobile OR :format => ‘mobile’.
I had a small typo in my previous code. This works now.