Using and Testing ActiveRecord/Rails Observers

October 27, 2007 on 2:31 pm | von Alexander Lang | 2 Kommentare
social feed

We recently introduced a new feature in autoki called the social feed. It’s basically a yellow box displaying any events on the platform relevant to the current user, like a friend has posted a new photo, or a new interesting car was uploaded. The data model behind this is pretty straightforward, we have a FeedEvent class and all kinds of subclasses, e.g. a MessageReceivedEvent. Each event belongs to a user and an event source, in this example the user would be the user who received the message and the event source would be the message itself. For each user, we simply display all the events that belong to him or her.

Now the question was this: How do we create these events? The most straightforward way would probably have been to create them in the models, so the Message model would have an after_create callback that created the event. What we didn’t like about this solution was that we would put a whole bunch of logic into the models that didn’t really belong there. Why would a Message care if there was some kind of event feed? Plus these events would be all around in our unit tests and make the bloated and probably sloooow (again). So we wanted to use the observer pattern to remove the creation of the event from the models.

weiterlesen…

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Railsconf Europe 2007 Roundup 1 (rspec)

September 24, 2007 on 10:58 pm | von Alexander Lang | 1 Kommentar

Last week was RailsConf 2007 in Berlin. Only a couple of days have passed and it already seems so far away. Time for some blogging before everybody forgets that it even took place and nobody’s going to read this :) So here’s the interesting part of the sessions I attended:

A Half-day of Behavior-driven Development on Rails (rspec)

This was the first session on tutorial day and for me one of the most interesting. It basically gave a looong introduction to behavior driven design, how it evolved from things like TDD and who realized what while enganged in which project back in the good old times. One of the interesting parts for me was when they talked about the whole story writing/specification process. I had heard most of it before but it was a good refreshment. The central statement was to write “Software that matters”, and to achieve this, you’d have to get the specs right - as we XPers know this should be done by collecting user stories. The suggested format for such a story was this:

weiterlesen…

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Using Mocha - A review

August 1, 2007 on 1:10 am | von thilo | 1 Kommentar

For aprox. 3 months we have been using mocha now. And we promised to get back to this subject when we passed our 2000th revision.

In this post I’d like to share some expirence we made while using mocha. But first a short introduction to mocha taken from the rubyforge page.

Mocha is a library for mocking and stubbing using a syntax like that of JMock, and SchMock. One of its main advantages is that it allows you to mock and stub methods on real (non-mock) classes and instances.

We started to use mocha on an existing test suite and changed our test code in place when we wrote a new test or had to update old ones. The transition was mostly painless, there were three things where we stumbled.
weiterlesen…

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Endlich wieder grüne Unit Tests (updated)

March 31, 2007 on 8:53 am | von Alexander Lang | keine Kommentare

colored.png

Ich bin in den vergangen Tagen über mehrere Blogeinträge gestolpert, die sich mit dem Thema Farben in Unit Tests (also , bei deren Ausführung) beschäftigt haben. RedGreen ist etwas unelegant, da man statt einfach rake einzutippen rake | redgreen schreiben muss.

Mit diesem kleinen Patch und dem colored Gem geht dann doch alles vollautomatisch. Toll.

Update: gerade ist mir aufgefallen, dass die Tests, wenn man sie innerhalb von TextMate ausführt, recht unansehnlich werden, da TextMate die entsprechenden Codes plain ausgibt, statt die Schrift farbig werden zu lassen. Bisher hatte ich oben genannten Patch in eine Datei colorized_tests.rb gepackt und diese mittels require File.expand_path(File.dirname(__FILE__) + '/colorized_tests')am Ende von test_helper.rb eingebunden. Um die Farbcodes in TextMate abzustellen, habe ich noch ein unless ENV["TM_PROJECT_DIRECTORY"] dahintergehangen. Jetzt sehen die in TextMate ausgeführten Tests wieder wie gewohnt aus, und bei rake gibt’s trotzdem Farben. Cool.

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Wir machen unseren Tests Beine

March 30, 2007 on 8:37 pm | von thilo | 1 Kommentar

Da unsere vielen Tests mittlerweile ein wenig lange brauchen, haben wir uns am heutigen Forschungstag mal wieder mit dem Problem Testing auseinandergesetzt. Das Ergebniss diesmal schon vorne weg: unsere erfolgreichste Entdeckung ist Mocha.
Mit diesem Framework lassen sich Stubs und Mocks mit realen Objekten verwenden. Es folgt ein kleiner Auszug aus unserem bisherigen Testcode.

Dauer: 795ms

Nach kurzem Studium des Mocha Cheat Sheets haben wir dann den Test wie folgt geändert.

Dauer: 49ms

Na wenn das keine signifikate Verbesserung ist. Auf Mocha gestoßen sind wir über den Testing Rails Blog, auf dem leider nichts Neues mehr zu passieren scheint. Eine kleine Übersicht von Stub-Frameworks mit problemspezifischen Einschätzungen fanden wir auf dem Blog von Jay Fields.

Wir werden Mocha in der nächsten Zeit in unseren Test integrieren, und bei der 2000ten Revision sagen wir euch wie lange unsere Test Suite läuft.

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Rails Fragment Caching - Testing and time based expiry

March 23, 2007 on 8:14 pm | von Alexander Lang | keine Kommentare

in the last days i started implementing caching for autoki.com. my first stop was this excellent rails caching tutorial over at railsenvy.com.

basically, rails offers 3 ways of caching page content:

  • page caching: an entire page gets stored on the hard disk and can then be served by apache instead of rails - very fast but almost useless for us, as every page has some dynamic element in this. we still consider it for some ajax calls.
  • action caching: also caches the entire page, but it’s still served by rails, which means before_filters for stuff like authnetication still work - still not for us, see above
  • fragment caching: as the name implies caches fragments of a page - yay, sounds good

fragment caching

the basics are really easy. first, you simply surround the parts of the page that you want to cache with a <% cache ' … <% end %>. this writes the fragment to a file in /tmp/caches and from now on, rails serves this part of the page from the cache.

this alone doesn’t get you any performance improvements yet, because your controller is still loading all the data from the database before rendering the view. to avoid this, you wrap your data loading code into unless read_fragment 'name' ... end blocks - now you page should be running lightning fast already.

the third problem to tackle is to clean the cache at the right time. this can either be done in the controllers by calling expire_fragment 'name' or by using so called sweepers. they are basically observe your models and clean the right fragments on events like after_create - so when you add a new user to the system, you can clean the list of users from the cache.
weiterlesen…

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Rails: FileColumn schneller testen durch Mocks

March 11, 2007 on 4:02 pm | von Alexander Lang | keine Kommentare

FileColumn ist ein wirkliches zauberhaftes Plugin fuer Ruby on Rails. All unsere Bilder-Uploads haben wir bisher damit umgesetzt. FileColumn bietet Helper, um Datei-Uploads zu bauen und kann die hochgeladenen Bilder natuerlich auch wieder anzeigen. Das eigentlich schoene ist aber die Integration mit RMagick, einem Ruby-Binding fuer ImageMagick, wodurch sich Bilder on the fly skalieren sowie beschneiden lassen und die verschiedenen Versionen dann automatisch im Dateisystem landen. Alles, was man dazu braucht, ist eine Zeile Code im Model, z.B.

Dieser Code erzeugt neben der Originalversion 3 Kopien: Eine 238 Pixel breite und entsprechend des Bildformats hohe, eine gestauchte, genau 23 x 35 Pixel grosse und eine genau 73 x 73 Pixel grosse, beschnittene Version.

So weit alles schoen. Das einzige Problem war, dass unsere Unit-Tests durch FileColumn ganz schoen langsam wurden. Bei jedem Testdurchlauf, der irgendwas mit Bilder zu tun hatte, wurden jedes mal mehrere skalierte Versionen erzeugt, was natuerlich Rechenzeit kostete. Die Loesung haben wir letzte Woche dann endlich mal zusammengehackt, und sie sieht so aus: Ein Modul, was von FileColumn installierte Callbacks ausser Gefecht setzt, wird in ein Mock des Models eingebunden, aber der Reihe nach. Hier das Modul, gelegen in test/file_column_mock.rb:

In unserem Beispiel wollen wir die Klasse User von ihrer FIleColumn-Last befreien. Dazu legen wir in test/mocks/test eine Datei user.rb an und fuellen sie mit folgendem Inhalt:

Der Effekt des ganzen ist, dass die Original User-Klasse aus app/models nochmals geoeffnet und mehrere Methoden, die normalerweise automatisch beim Setzen des photo-Attributs loslaufen, umd die skalierten Versionen zu erzeugen, durch Ueberschreiben ausser Gefecht gesetzt werden.

Das war’s. Und schon fliegen die Tests wieder mit voller Geschwindigkeit.

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Deine Tests wissen die Antwort.

February 25, 2007 on 3:49 pm | von thilo | keine Kommentare

Nachdem wir vor kurzem auf Rails 1.2.2 umgestiegen sind, verbrachte ich letztens einige Stunden damit die Ursache für folgenden Fehler zu finden, der beim starten von mongrel auftrat: 'remove_const': cannot remove Object::ModelTranslation (NameError) Die Logfiles zeigten, dass es Probleme beim Laden von Abhängigkeiten für Globalize gab. Allerdings war die Ursache völlig unklar. Ein Aufruf unserer Unit Tests mit rake lieferte dann die banale Lösung: der Datenbankserver lief nicht.

Das lehrt mal wieder, immer die Tests laufen lassen, wenn es Probleme gibt!

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

Testing helpers in Ruby on Rails 1.2

February 21, 2007 on 1:57 pm | von Alexander Lang | 5 Kommentare

We are just migrating one of our projects from Rails 1.1.6 to 1.2.2. One of the problems we encountered was, that Recipe 44: Write tests for your helpers from Rails Recipes (by the way Advanced Rails Recipes will come out in Augut 2007) is not working anymore. The line

@controller.send :initialize_current_url

resulted in a

After some messing around, we found out that the following setup method solves this:

Happy testing :)

post to del.icio.us Diese Seite zu Mister Wong hinzufügen

  • RSS keiala

  • RSS open source projects: commits

  • Tags

  • Archives

  • Meta


  • Powered by WordPress with Pool theme design by Borja Fernandez.
    Entries and comments feeds. Valid XHTML and CSS. ^Top^