Comment on Enabling/disabling observers for testing by Luke Redpath

Thu, 10 Apr 2008 03:11:21 -0700

I've done some testing around observers recently and we came up with a simple way of preventing observers from interfering with our tests - it's not as flexible as your solution but I'm not sure it needs to be that flexible.

Given a model Foo, and an observer FooObserver, in our Foo tests, in the setup, we would stub the Foo#notify method (we are using mocha):

class FooTest < Test::Unit::TestCase
  def setup
    @foo = Foo.new
    @foo.stubs(:notify) # no observers get called
  end
end

We would then test our Observers separately:

class FooObserverTest < Test::Unit::TestCase
  def setup
    @observer = FooObserver.instance
  end
end

This allows us to test our objects and their observers in isolation; in general you can rely on Rails to do the right thing and make sure your observers get called in the right place although you could also write some integration/functional tests to confirm this.