I've just started using Observers in a Rails application I'm creating and found out that in order to have them picked up by rails you have to manually register the Observers within your environment.rb file, like so:

  1. config.active_record.observers = :my_observer

I like to have as much coverage for any code I write in Rails, such as associations I've created, validation rules etc. I'm not testing the validation itself (Rails' tests have that covered) what I'm testing is that I've actually applied the validation rule.

So I figured that I should do the same for the Observers which should be registered. I couldn't find any references to anyone else doing this so after a little bit of digging I've come up with the following approach for use with RSpec:

matchers/observer_matchers.rb :

  1. module Matchers
  2.   module ObserverMatchers
  4.     #
  5.     # Used to check that an observer has been registered
  6.     #
  7.     class BeRegistered
  9.       def initialize(observer_name)
  10.         @observer_name = observer_name
  11.       end
  13.       def matches?(observers)
  14.         @observers = observers
  15.         @observers.include?(@observer_name)
  16.       end
  18.       def failure_message
  19.         "expected observer with name of '#{@observer_name}' to be registered but wasn't"
  20.       end
  22.       def negative_failure_message
  23.         "expected observer with name of '#{@observer_name}' not to be registered but was"
  24.       end
  25.     end
  27.     #
  28.     # Usage:
  29.     #
  30.     # ActiveRecord::Base.observers.should be_registered(:user_observer)
  31.     def be_registered(*args)
  32.       BeRegistered.new(*args)
  33.     end
  35.   end
  36. end


  1. require File.dirname(__FILE__) + '/../spec_helper'
  3. describe UserObserver do
  5.   it "should be registered with the application" do
  6.     ActiveRecord::Base.observers.should be_registered(:user_observer)
  7.   end
  9.   ...
  10. end

It really is quite simple, but feel free to use the matcher if you want. Consider it released under BSD licence, no guarantees etc.

Comments are disabled on this post.