Rails system tests for multiple screen sizes

posted by Ayush Newatia
19 October, 2022



This post was extracted and adapted from The Rails and Hotwire Codex.

Rails system tests simulate a user’s actions in a web browser so it’s akin to the app’s real world usage. In a responsive app, this means testing on multiple screen sizes as well.

Capybara, the tool used by system tests under the hood, has a method to resize the current window during a test run. But, since the tests are not run in a set order, any test that resizes the window needs to restore the size after it’s done. Otherwise, subsequent tests run in that window could fail.

Let’s take a look at how to write a set of system tests for mobile screens.

Mobile system tests

Create a subclass of ApplicationSystemTestCase specifically for mobile. It will resize the window in the setup and teardown methods that are invoked before and after each test case.

require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  WINDOW_SIZE = [1400, 1400]
  driven_by :selenium, using: :chrome, screen_size: WINDOW_SIZE
end

class MobileSystemTestCase < ApplicationSystemTestCase
  setup do
    visit root_path
    current_window.resize_to(375, 812)
  end

  teardown do
    current_window.resize_to(*ApplicationSystemTestCase::WINDOW_SIZE)
  end
end

We can use this new base class to write tests aimed at mobile screens. Let’s say the navigation bar shows a burger menu only on mobile. We can test that as:

require "application_system_test_case"

module Mobile
  class NavigationBarTest < MobileSystemTestCase
    test "can access sign up page via burger menu" do
      visit root_path

      find(".navbar-burger").click
      click_on "Sign Up"

      assert_current_path sign_up_path
    end

    test "can access login page via burger menu" do
      visit root_path

      find(".navbar-burger").click
      click_on "Log in"

      assert_current_path login_path
    end
  end
end

Running the system tests will now resize the window for the above two tests and restore the size back to desktop after they’re done!

$ bin/rails test:system

If you liked this post, check out my book, The Rails and Hotwire Codex, to level-up your Rails and Hotwire skills!