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.
ZombieSighting.delete_observers
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 = Factory.build(:zombie_sighting)
end
it 'should generate a new notification' do
lambda {
@obs.after_create(@thing)
}.should change(Notification, :count)
end
end
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).
2 comments so far ↓
Luis Hurtado // July 28, 2009 @ 12:15 PM
Thanks a lot.
Karmen Blake // November 13, 2009 @ 08:55 PM
Thank you very much!!!! You just relieved me of hours of frustration!
Leave a Comment