Observer behavior differences between DEV and TEST environme

Hi all !

I’m having an issue and I can’t seem to make heads or tails of it.

I am attempting to add an observer to a model object. I created
app/models/greenback_transaction_observer.rb, inherited from
AR::Observer, defined methods, registered in config/environment.rb,
but things don’t work…

So, I took a step back and put in the following code:

class GreenbackTransactionObserver < ActiveRecord::Observer
%w( after_find after_initialize before_save after_save
before_create after_create before_update after_update
before_validation after_validation before_validation_on_create
after_validation_on_create
before_validation_on_update after_validation_on_update
before_destroy after_destroy ).each do |method|
define_method(method) do |txn|
txn.logger.info “#{method} (observer)”
true
end
end
end

My model looks like this:

class GreenbackTransaction < ActiveRecord::Base
%w(before_save after_save).each do |method|
send(method) do |txn|
txn.logger.info “#{method} (model)”
end
end
end

If I start the console and do some operations on the model, things
work out fine. If I run my tests, the observer never fires. I added
some logging statements to Rails’ observer.rb, and I see the calls to
update, and the subsequent notifications of my observer in development
environment, but not in the test environment.

The logs look like this:

GreenbackTransaction Load (0.000000) SELECT * FROM
greenback_transactions LIMIT 1
:after_initialize == #notify – BEGIN (1)
GreenbackTransactionObserver#update(:after_initialize,
#<GreenbackTransaction:0x362f6d8 …>)
after_initialize (observer)
:after_initialize == #notify – END

The BEGIN line with the 1 in parens is the result of calling
self.class.count_observers.

On the other hand, when I run the tests, the log looks like this:

GreenbackTransaction Load (0.000000) SELECT * FROM
greenback_transactions WHERE (greenback_transactions.id = 1411) LIMIT
1
:after_initialize == #notify – BEGIN (0)
:after_initialize == #notify – END

You can see there are no observers. Where have they gone ? Nobody
knows…

config/environment.rb looks like this:

Rails::Initializer.run do |config|

config.active_record.observers = :greenback_transaction_observer
end

So, I think I’m doing all the steps in the right order, and everything
should be fine. Except things aren’t working correctly.

Anybody sees anything obviously wrong from the above ?

Thanks !

2006/5/24, Francois B. [email protected]:

I am attempting to add an observer to a model object. I created
app/models/greenback_transaction_observer.rb, inherited from
AR::Observer, defined methods, registered in config/environment.rb,
but things don’t work…

Okay, I found the problem:
http://blog.teksol.info/articles/2006/05/24/single-table-inheritance-and-active-record-observers

Short answer: it seems I should have observed my STI subclasses, not
only the main class.

Enjoy !