Forum: Ruby on Rails How should I test this?

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.
Gavin M. (Guest)
on 2009-05-06 15:37
(Received via mailing list)
Hi all

In my app I'd like to send a request to google sitemaps indexer after
a new post is created.

This would take place in the post_observer and would look something
like this:

require 'net/http'
require 'uri'
class PostObserver < ActiveRecord::Observer

include ActionController::UrlWriter
default_url_options[:host] = "mydomain.com"

  def after_create(post)
    Net::HTTP.get('www.google.com',  '/ping?sitemap=' + URI.escape
(sitemap_url))
  end
end

How could I write a test for this?
Also - how could I disable the actual request while running in test
mode?


Thanks

Gavin
Phlip (Guest)
on 2009-05-06 17:20
(Received via mailing list)
Gavin wrote:

> include ActionController::UrlWriter
> default_url_options[:host] = "mydomain.com"
>
>   def after_create(post)
>     Net::HTTP.get('www.google.com',  '/ping?sitemap=' + URI.escape
> (sitemap_url))
>   end
> end
>
> How could I write a test for this?

Firstly, after_create should not call the service directly - it should
call a
method in a GoogleApi module that calls the service. (See the thread "no
sql in
the controller guideline".)

> Also - how could I disable the actual request while running in test
> mode?

Use Mocha to introduce a mock.

Call the real service one time and p the result out. Copy the result
into the
test code and configure a test to mock either the Net::HTTP or the
GoogleApi.
The mock will return your recorded result.

--
   Phlip
   http://flea.sourceforge.net/resume.html
Gavin M. (Guest)
on 2009-05-06 19:58
(Received via mailing list)
> Firstly, after_create should not call the service directly - it should call a
> method in a GoogleApi module that calls the service. (See the thread "no sql in
> the controller guideline".)

Would this apply to model_observers too?
Phlip (Guest)
on 2009-05-06 22:20
(Received via mailing list)
Gavin wrote:
>> Firstly, after_create should not call the service directly - it should call a
>> method in a GoogleApi module that calls the service. (See the thread "no sql in
>> the controller guideline".)
>
> Would this apply to model_observers too?

Yes; MVC theory suggests observers are controllers. We all wish
observers did
not exist, and controllers simply watched everything! Observers are just
exposed
plumbing...

--
   Phlip
   http://flea.sourceforge.net/resume.html
Gavin M. (Guest)
on 2009-05-06 22:38
(Received via mailing list)
So instead of sending an email after a user is created (for example)
from the observer, It would be better to have the controller send it
or call a model method to send it?
This topic is locked and can not be replied to.