Unit testing an Observer


#1

Hi,

How can I unit test an Observer? Its new method is private, and I can’t
find any documentation on that topic.


#2

Fernando P. wrote:

How can I unit test an Observer? Its new method is private, and I can’t
find any documentation on that topic.

Can’t you trigger the observed event - such as Frob.create - and then
detect the
side-effect the observer produces?


Phlip
http://flea.sourceforge.net/resume.html


#3

Here’s part of a spec (with some details changed/omitted) for an
observer
that notifies another system via a SOAP API that a user was created:

describe UserObserver do

before(:each) do
@observer = UserObserver.instance
end

it “sends notification of creation” do
user = mock_model(User, :email_address => “removed_email_address@domain.invalid”, …)
expected_attributes = {
:id => user.id,
:“email-address” => user.email_address,

}
SomeApi.should_receive(:user_created).with(:attributes =>
expected_attributes).and_return(“created”)
@observer.after_create(user)
end
end

When testing your model that this observer observes, you might want to
use
the no peeping toms plugin [
http://github.com/pat-maddox/no-peeping-toms/tree/master ] to prevent
observers from being notified.

Regards,
Craig


Craig D.
Mutually Human Software
http://mutuallyhuman.com


#4

@observer = UserObserver.instance

Thanks Craig that was the trick!

I don’t need NoPeepingTom as I put expectations on observer’s method
calls so I can intercept them and just make sure that the correct
methods are invoked.