Test JavaScript Interactions with a Real Browser

Learn and test the interaction of JavaScript with a real browser.

We'll cover the following

If we have features that require JavaScript or won’t work if our JavaScript is broken, we need to test them in a real browser. While unit tests could help, they won’t give complete confidence because we need to see the JavaScript executing in context. Because we’ve set our system tests to use :rack_test, that means they won’t use a real browser, and JavaScript won’t be executed. We need to allow a subset of our tests to actually use a real browser (which is what Rails’ system tests do by default).

To that end, we’ll create a subclass of our existing ApplicationSystemTestCase that will be for browser-driven tests. We’ll call it BrowserSystemTestCase, and it will configure Chrome to run the testsIf we are using RSpec, this is something we’d implement with tags, as that is a more natural fit for RSpec, but to reiterate, the testing framework doesn’t matter greatly. We’re only talking about a strategy at this point.. The default configuration for Rails is to use a real Chrome browser that pops up and runs tests while we watch. This becomes difficult to get working in a continuous integration environment.

Fortunately, it’s unnecessary because Chrome has a headless mode that works exactly the same way as normal Chrome but does everything offline without actually drawing to the screenThis is what we’ve been using to create the screenshots for this course..

Setting up headless chrome

We’ll spare the boring details about Linux, Docker, running-as-root, and shared memory. Instead, we’ll skip straight to the opaque configuration needed to make this work. First, we’ll register the driver at the top of application_system_test_case.rb:

Get hands-on with 1200+ tech skills courses.