Not sure what the original problem was. Ended up rewriting the code anyways and adding rspec for unit testing.
Unit tests pass now locally as well as on staging site. AFAICT the problem is gone.