please don’t use before(:all)

Please do not use “before(:all)” (in rspec) unless it is imperative for performance reasons. Even then, it should only be used with the utmost care given towards any global or shared state, and with no expectations on order of the spec run. You will cause strange build failures if you do not heed this warning.

Each individual example (”it” blocks) should be able to run by itself or in any order and the example group (”describe” blocks) may run in any order, even in random order.

Corollaries:  If you change any global or shared state inside an example, please ensure that you reset it to a baseline before the next example.  If you depend on any global shared state, please set it to a baseline before this example.  Both of these are achieved easily with a before(:each) block (or after(:each) in some cases).

Nine times out of ten, when I see a weird sporadic build failure and there is a before(:all) nearby, I can fix it merely by changing it to a before(:each).  The original author of the spec assumed that it would always run front to back and then proceed to change global or shared state in some of examples (sometimes inadvertantly).

Although I’ve phrased this advice for rspec, it applies equally to test/unit in ruby, or xUnit on any platform.

Tags: ,

2 Responses to “please don’t use before(:all)”

  1. Patrick says:

    Uh-oh.. I can’t help but feel like I shoulder some of the blame for this post :)

  2. nick says:

    If indeed you shared blame for this, you certainly weren’t the first nor the last. ;)

Leave a Reply