Run Tests When Code Changes

Run Tests When Code Changes

. 2 min read

As we develop code, we often want to confirm whether the code works; that is why we write tests that compose an automated test suite. In this post we consider how to make getting the feedback from running tests as natural and frictionless as possible.

In theory, the earliest point at which we could need such feedback is as soon as we’ve made any change to the code. The notion is that we can use a tool to watch the filesystem for changes, and run our tests as soon as the code has changed. That way we can focus on the code we’re writing, and not on routine tasks such as saving documents or triggering test runs. Whenever we’re interested in the test output, we can simply switch to that terminal and evaluate the output.

In a Ruby project, how to run tests when code changes

Configure Guard

First, add guard-rspec to our Gemfile and (following its README.md), run bundle exec guard init rspec. This will add a barebones Guardfile that is compatible with Rails projects.

That generated Guardfile will specify an RSpec command (bundle exec rspec). This is the command with which Guard will run our tests. We can customize that RSpec command as usual (e.g. one commonly helpful option is --documentation).

Run tests using Guard

Spin up Guard

Now that Guard is configured, from the repo root, run bundle exec guard --clear. This will spin up the Guard console. The --clear flag makes it so that the terminal output is cleared before each run, so that only the results of the latest run appear in the output.

Run tests

Inside of the Guard console, press enter to run all tests. This is equivalent to running bundle exec rspec.

The main utility of Guard, however, comes from the fact that it automatically will run some tests when certain files change. For example, try saving a test file and then flip back to the Guard console — note that those tests were executed.

It is helpful to enable “auto save” in our favorite code editor (outside the scope of this document, but this makes sense particularly when working in a git repo).

Tweaks

If we find that Guard isn’t running some tests when it seems like it should — for example, when we change the CSV file that is an input to certain RSpec tests — it’s possible to setup custom rules in the Guardfile, such as “when the contents of a file whose filename contains pattern ‘xyz’ changes, run the following tests”.

When using the --clear option, it is helpful to know about the pause command, available in the Guard console. Executing pause prevents Guard from running tests again. This is helpful when inspecting a large error output and making a few changes in the code — in that case we don’t want to immediately re-run tests on every change. Execute the pause command again to re-enable Guard.

In non-Ruby projects, too!

The tooling to implement “run tests whenever the code changes” is available in many common development environments. Some other examples: