Unit testing an Observer

Hi,

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

Fernando Perez 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?

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 => “user@example.com”, …)
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

@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.