...

/

Running Tests: Providing Support for JavaScript

Running Tests: Providing Support for JavaScript

Learn to set up testing with JavaScript support.

Running tests that rely on JavaScript

OK, let’s take this up a notch. Setting up testing with JavaScript support is not going to be so straightforward with Docker. But you are ready to handle it.

Imagine that we have an enhanced version of our /welcome page that has extra behavior that only works with JavaScript enabled. In fact, when functioning correctly, this JavaScript literally adds the message “ENHANCED!” on the page.

Modify index.html.erb

Here is a rather crude implementation in app/views/welcome/index.html.erb:

Press + to interact
<% content_for :head do %>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded",function(){
document.getElementsByTagName('h1')[0].append(' ENHANCED!');
});
</script>
<% end %>
<h1>This page has been viewed <%= pluralize(@page_hits, 'time') %>!</h1>

Modify application.html.erb

We also need a tweak to app/views/layouts/application.html.erb to make this work:

Press + to interact
<!DOCTYPE html>
<html>
<head>
<title>Myapp</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application',
media: 'all',
'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= yield :head %>
</head>
<body>
<%= yield %>
</body>
</html>

Adding scenario to test JavaScript behavior

Let’s add a second scenario to our page-views-spec.rb in spec/system to test this behavior:

Press + to interact
require 'rails_helper'
RSpec.describe "PageViews" do
it "shows the number of page views" do
visit '/welcome'
expect(page.text).to match(/This page has been viewed [0-9]+ times?!/)
end
it "is enhanced with JavaScript on", js: true do
visit '/welcome'
expect(page).to have_text("ENHANCED!")
end
end

As per the RSpec convention, we have indicated that this new scenario is only expected to pass with JavaScript enabled, by specifying js: true ...