zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

Testing ActiveRecord Observers

July 25, 2009 by nap · Comments

Need to unit test those pesky ActiveRecord observers you’re using? I don’t use em often, but there are times when they’re definitely useful. Fortunately, since AR::Observer leverages Ruby’s Observable module all you have to do is call MyModel.delete_observers in your test setup or before block.


Better yet, add the exclusions to your test or spec helper file. Then you can unit test your models comfortably in isolation, and write tests for your observers that look like this:

describe Observer
  before(:each) do
    @obs = ZombieSightingObserver.instance
    @thing =

  it 'should generate a new notification' do
    lambda { 
    }.should change(Notification, :count)

We wouldn’t want to couple zombie sightings too tightly with notifications, after all, as that might anger them even further (zombies are known to be crazy about SRP).

blog comments powered by Disqus