Running Rails in the Background

Learn how to run Rails in the background using the Spring gem.

One difference between TDD in a Rails context and TDD in SUnit’s original Smalltalk environment is that testing a Rails program typically requires that Ruby be started from the command line and that the Rails environment is loaded. Starting from the command line can take quite a bit of time on even a moderate-size Rails project. If we’re trying to run, say, a single file’s worth of tests that we expect to take about a second, having the Rails startup take more than a minute can break our flow. In contrast, the Smalltalk tests reside inside the same live process as the code and can therefore start instantly.

Simulate Smalltalk Behavior

One way to simulate the Smalltalk behavior in Rails is to not restart the Rails application on every test. A way to avoid restarting the Rails application is to have it already running in a background task and use the existing background application. Rails ships with the Spring gem, which does just that. Here’s how to use Spring to speed up our tests.

Installing Spring

Spring is a gem. It comes with Rails by default and we’ll want it in our Gemfile. There are a couple of helper gems that we’ll probably also want. All these gems go in the development group of the Gemfile:

Get hands-on with 1200+ tech skills courses.