Forum: Ruby on Rails Unit testing an Observer

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
059ed46172a087063ce26250e44c8627?d=identicon&s=25 Fernando Perez (fernando)
on 2009-05-14 14:55
Hi,

How can I unit test an Observer? Its new method is private, and I can't
find any documentation on that topic.
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2009-05-14 15:19
(Received via mailing list)
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?

--
   Phlip
   http://flea.sourceforge.net/resume.html
B14575f0ca69f10938fdd67e7156e0e1?d=identicon&s=25 Craig Demyanovich (Guest)
on 2009-05-14 17:09
(Received via mailing list)
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


--
Craig Demyanovich
Mutually Human Software
http://mutuallyhuman.com
059ed46172a087063ce26250e44c8627?d=identicon&s=25 Fernando Perez (fernando)
on 2009-05-14 19:18
> @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.
This topic is locked and can not be replied to.