Last Updated: February 25, 2016
·
1.387K
· perldork

Class variables in Rspec tests - reloads will happen during testing!

As is the case when a ruby application runs in a multi-process web container (phusion passenger for example), during your rspec test runs, classes can be reloaded - meaning any class-level variables that are set cannot be counted on across tests, even within the same describe block.

We have a few classes that act as API wrappers for external services that we like to be able to have off by default in our test environment and on by default in production - we initially used class variables for these, but found that the state was getting reset across runs.

Fix: move the initial states into config/application.rb and config/environments/* and use those to initialize the cattr_accessor definitions at the top of the classes.