Ruby rspec Unit Tests

Posted 28 January 2015

I write quite a lot of unit tests, but I'm trying to write some tests on someone else's code which is heavily integrated with external systems. It's quite a challenge, and not one I'm especially used to (I don't usually work on other people's code, and if I do, it tends to be to add an additional test here and there, rather than starting from scratch).

In this particular case, I'm trying to track down a bug that's been intermittently experienced in real-world use. I've got a theory about where the problem is, so have been trying to get that bit of code tested. I'm not totally familiar with the code though, so have found myself looking at the (probably) offending method and writing tests for each of the methods it calls. So far so good, although I can't claim an especially comprehensive test suite on those methods, I'm pretty confident they're not the problem.

Now comes the big work though - I've got to mock/stub out all kinds of stuff, pre-load those things before the test runs and create reams of test data that the mocks need to return. The method is pretty central to the code, so it takes a lot in and passes a lot out. None of this is especially unique, and I'm sure many developers would sympathise with my predicament. It's just very slow going and feels like there's a whole lot of "set up" before I can get near the "real work" of finding and fixing the bug. The other frustrating thing is that I strongly suspect I'll end up refactoring this method and the one that calls it to fix the bug.

One thing that I do really like is the ability to stop a method using some function or method and use your test version of it instead. This sort of thing is nice:

For code like this:

def Foo()
  bar =
  gaz = bar.long_expensive_work()
  gaz = gaz + 1
end can test it like this (without calling long_expensive_work()):

describe '#Foo' do
  bar = double()
  allow(Bar).to receive(:long_expensive_work).and_return(5)
  it "works" do
    expect(Foo).to be 6

(I found the principles above here:, although the above is paraphrased from some code I was working on earlier at work)

I don't really have a point here, other than to say "me too" to all the developers who's gone before me and will follow me on this age-old problem of working with code that wasn't written with testing in mind.

Tags: #ruby #rspec #unit testing

More blog posts:

Previous Post: Duplicity and Amazon Glacier  |  Next Post: Peeked - Git Connected Pico CMS Editor

Blog Archive