Back to all articles

Using guard gem in a project with multiple modules

Tests are important

guard illustration Regardless of what I work on – frontend or backend – the most important thing for me is to be sure that everything is working properly after my changes. That’s why, in my opinion, tests are essential.

In order to not have to remember about executing tests on every change, I use guard gem, which does it automatically. So I always add guard to every project.

Complicated project with lots of modules

Lets assume we have a project that consists of separate modules, each having its own test suite. Theoretically you could setup guard for every module separately but then you would have to monitor separate terminal tabs for each module to be sure that everything is green.

It’s easy to get lost in tabs, so I wanted to setup guard in the usual way, to have one terminal with the guard that will watch changes from all the modules.

I found the watchdir option, which I thought should do the job, but it didn’t work the way I expected. I touched base with the guard core team and it turned out that this option is just an optimization for really large projects in order to not kill your processor or hard drive.

New option in guard to the rescue

After discussing the issue with the guard team, I decided to implement a new option for that. The new option is called chdir. There are changes to both guard and guard-rspec, they have been merged into a master and are waiting for release.

Assuming you have your project setup like here, so you have all the usual tests in spec directory but you also have the moduleA directory with a separate test suite in moduleA/spec, you can use guard to monitor all your modules running the usual command bundle exec guard start and having Guardfile configured in this way:

There are 4 important things there:

  • chdir option passed to guard method
  • changes in cmdguard needs to change directory to execute your tests in moduleA
  • a prefix needs to be added to every pattern
  • everything is done in a loop for every test suite

Now you can run bundle exec guard start and check that it also monitors also tests in the moduleA directory.

Share this article: