Running tests under spork with apps using Thinking Sphinx

My recent post on thredUP now using spork to speed up our test suite was missing a key part.  This week Liah, one of our developers, noticed that the models weren't getting reloaded properly when the code was changed.  This was the underlying value that spork promised (not having to restart the app for every test run) so something had to be amiss.  Sure enough, after a little digging, I found out that thinking sphinx has this annoying preference to preload rails models.  This causes the models to be loaded once, during spork boot up rather than on each run.  Yikes.

The fix for this uses Spork's handy "trap_method".  They even have a wiki page dedicated to it: https://github.com/timcharper/spork/wiki/Spork.trap_method-Jujutsu. They don't mention thinking sphinx on there but after a little digging, I found out that the code I need to add to my prefork methods was something like:

The problem I soon realized was then when you tried to run our tests without spork it would error due to this trap_method.  The fix for this was to use a check to see if spork was being used:

In the end these were fairly easy fixes but the documentation for the specific sphinx method was a little thin out there so I thought I'd throw this together and hopefully someone else will find it helpful.