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.
Fernando P. (Guest)
on 2009-05-14 16:55
Hi,

How can I unit test an Observer? Its new method is private, and I can't
find any documentation on that topic.
Phlip (Guest)
on 2009-05-14 17:19
(Received via mailing list)
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
Craig D. (Guest)
on 2009-05-14 19: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 => 
"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
Fernando P. (Guest)
on 2009-05-14 21: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.