Last Updated: February 20, 2016
·
3.281K
· jcf

Test Observers with Rails 3.2.6

There's a No Peeping Toms gem that extended ActiveRecord to make it easier to test observers.

Unfortunately, No Peeping Toms doesn't work too well with recent versions of ActiveRecord (>= 3.2.3), so I replaced the functionality using public APIs within ActiveModel::Observer.

# spec/support/managed_observers.rb

module ManagedObservers
  def with_observer(*observers)
    ActiveRecord::Base.observers.enable(*observers)
    yield
    ActiveRecord::Base.observers.disable(:all)
  end

  alias_method :with_observers, :with_observer
end

RSpec.configure do |config|
  config.include ManagedObservers

  config.before(:all) do
    ActiveRecord::Base.observers.disable(:all)
  end
end

That small snippet makes it possible to enable individual observers ad hoc.

describe Person do
  it 'observes things' do
    with_observer(:person_observer) { Person.new.save }
  end
end