Making the Test Pass

Learn how to make the test pass and add jQuery methods to the test.

JavaScript environment

In this section, we’ll set up the JavaScript and present some passing code without unit testing. In the next chapter, we’ll set up JavaScript unit-testing tools and see how we might test-drive JavaScript features.

Rails 5.1 made two important changes to the JavaScript environment:

Webpack is an optional replacement for the Rails asset pipeline and has the same general purpose. It takes files that might be written in JavaScript, CoffeeScript, TypeScript, Elm, or another language, and builds them into JavaScript files that can be passed to the browser. Webpack’s advantage is that it’s flexible, it’s tied into the current JavaScript ecosystem, and it allows for a much wider range of JavaScript and CSS tools to be built into the Rails project. The disadvantage is that Webpack is quite complicated, but the Webpacker extension written by the Rails team provides defaults that will allow us to get pretty far.

JavaScript managing package dependencies

Even though jQuery isn’t part of the Rails default, it’s still probably the quickest way to handle our little feature here, so let’s add it back in via Webpack. Rails use a tool called Yarn to manage JavaScript package dependencies. Yarn is the JavaScript equivalent of Bundler and even has some of the same developers.

When we generated the Rails application, we included Webpacker, but if we haven’t yet, we can add it with this:

$ bundle exec rails webpacker:install

We can add jQuery to the dependencies with the following:

$ yarn add jquery

The package.json file dependencies

We can see the full list of dependencies in the package.json file, which is the equivalent of Bundler’s Gemfile, and in the yarn.lock file, which matches Gemfile.lock. All the code is stored in the node_modules directory, which will become quite large.

The jQuery method

There’s one other configuration piece. In the file config/webpack/environment.js, we need to register jQuery as owning the global $ and jQuery methods so that other modules that use them will correctly link to them:

Get hands-on with 1200+ tech skills courses.