Responsive layout tests with Capybara and RSpec

Responsive layout tests with Capybara and RSpec

Responsive web design is not a feature these days, bur rather a must. So, while implementing responsive layout in your application, you might find helpful adding verifications to your acceptance tests and ensure accessibility/inaccessibility to your app functionality depending on the screen size.

Capybara has a method to resize the browser window:

Capybara.current_session.driver.browser.manage.window.resize_to(width, height)

To cover all layout breakpoints you can create responsive helpers with required browser size and default one:

module ResponsiveHelpers

  def resize_window_to_mobile
    resize_window_by([640, 480])
  end

  def resize_window_to_tablet
    resize_window_by([960, 640])
  end

  def resize_window_default
    resize_window_by([1024, 768])
  end

  private

  def resize_window_by(size)
    Capybara.current_session.driver.browser.manage.window.resize_to(size[0], size[1]) if Capybara.current_session.driver.browser.respond_to? 'manage'
  end

end

And integrate it in your test. After you run a test case, the browser window should be resized back to default size:

require "rails_helper"

RSpec.describe 'Inboxes responsive layout', js: true do

  subject{ page }

  describe "Up to mobile view" do

    before do
      resize_window_to_mobile
    end

    after do
      resize_window_default
    end

    describe 'hidden inbox actions' do
      it{ is_expected.to have_selector('.create_inbox_form', visible: false) }
    end

  end

end

For more details on this and other useful methods of Window, check the documentation.