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:

RUBY:
  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 :

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

models/user_observer_spec.rb

RUBY:
  1. require File.dirname(__FILE__) + '/../spec_helper'
  2.  
  3. describe UserObserver do
  4.  
  5.   it "should be registered with the application" do
  6.     ActiveRecord::Base.observers.should be_registered(:user_observer)
  7.   end
  8.  
  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.