Strategies for mixed AJAX/Regular Forms in Rails

Sickness and insomnia strike and so I’m sat up getting my pet-project up on Edge Rails and trying to get a mixed form working. Unfortunately, it’s something I’m not getting too far with.

Here’s the scenario, I have a form that contains areas for visitors to enter two addresses, billing and delivery. Within these forms I want to be able to provide users with the ability to enter their postcode and have their address automagically filled via. a webservice.

However, these addresses are merely objects that compose part of an outer object—`Order`. So, an order contains both a `billing_address` and `delivery_address`. The visitor needs to be able to submit the form and have the booking saved.

I have to own up to having been somewhat mollycuddled by ASP.NET’s Postback model, abstracting me from HTTP’s inherent request/response model.

Originally I expected to just be able to have a form within a form. So, along the lines of:

<%= start_form_tag(:action => "save") %>  ...  <%= form_remote_tag(:update => "results" %>    ...    
  <%= end_form_tag %>  ...  <%= text_field_tag :outer_field1 %>  <%= text_field_tag :outer_field2 %>  ...  <%= submit_tag "Save" %><%= end_form_tag %>

And then I would be able to post the inner form, have it’s results updated and then when I wanted to post the whole form (i.e. the 2 outer fields) I could do and the info would be posted to `save`. Unfortunately, that doesn’t seem to be the behaviour.

So, I’m trying to decide how best to proceed. My first thoughts were to follow ASP.NET’s design and include hidden field/s that would let me be able to determine what action the user had just performed.

Ah well, for the time being I’m open to suggestions, time to try and get some sleep!

Interesting things afoot with Spring

has posted about something appearing in the MVC framework within Java’s Spring framework —something he called smart defaults, or in ‘Rails speak’: convention over configuration.

Spring is one of the nicest frameworks I’ve used. It does require a fair bit of XML legwork to get it running, but, it is nevertheless very easy to extend—so you write less code.

Like Rails, the thing I appreciate most about it is it’s support for testing. Since it adopts a very strong design around it’s core Dependency Injection principles, it’s classes have a fantastically low coupling, making it very easy to write your code and (more importantly) unit tests. Because of it’s design, it encourages the developer to write high quality well tested code—something that I’ve increasingly noticed with Rails, it makes test-first easy.

However, it’s not quite as easy as `rails myapp` to get a new app going, but Matt’s excellent Equinox project does provide a base-app around which to fill, making it much easier to get up and going (something I’m never really much of a fan of).

Which reminds me, I must get a copy of his Spring Live book, although I’ve played with Spring and it’s MVC stuff a little, it deserves more of my time.

Integrating Typo with FeedBurner

I’ve started using Google Analytics to get an idea about the readership of my humble blog. Fortunately, it appears to be growing in visits (at around 60 per day at the moment), and the number of page views per visit also seems to be on the increase (around 1.8).

However, this is only part of the story—I also consume blogs via my preferred RSS reader (JetBrains’ Omea) which will be ignored through Google’s JavaScript. So, I decided to try using FeedBurner’s free service. In effect, FeedBurner take over control for providing your RSS feed to your subscribers, and capture a little information in the process.

Fortunately, it’s possible to use URL rewriting, which is even easier with Lighttpd. So, the snippet from my config file that does it all:

$HTTP["useragent"] !~ "FeedBurner" {  url.redirect =    ("/xml/rss20/feed.xml" =>    "http://feeds.feedburner.com/oobaloo")}

Stick that inside your site’s configuration section and you’re off and running. One thing to note though is that it’s important to check the user-agent to ensure that FeedBurner’s bots can still retrieve the RSS feed from my server, just that everyone else gets the burned feed.

Anyway, that concludes all for this working week, time for some booze and then some more Rails hackery over the weekend.

Two ActiveRecord Associations to same Model

I’ve been really busy so haven’t had time to blog much about the work I’ve been doing on various side projects, but this is something that’s been kicking around in my head (and I’ve not found a conclusive answer to) so I’m going to post here in the hope someone may help!

I was trying to have a model retain an association to another model class through two separate associations, for example:

class Order < ActiveRecord::Base  has_one :billing_address, :class_name => "Address"   has_one :delivery_address, :class_name => "Address" end

class Address < ActiveRecord::Base  belongs_to :orderend

But, for some reason this was causing me problems and it just wasn’t working at all. I would print the message I was getting, but don’t have it to hand (and am a little busy to knock up a sample). I’ll try and do that later tonight and update the post when I do.

In the end I solved it by instead having an attribute on the `Address` class that signified whether it was the billing or delivery address. But, nevertheless, a bit weird.

I’ve read in some places that this kind of thing can cause Rails to go loopy, and then in other places read it ought to work fine.

Anyone know whether this does work?

Test-Driven Implementation of a SOAP Client in Rails

For a project I’m working on at the moment I need to allow the visitor to enter address details, one of the improvements to a regular form is the inclusion of post-code lookups—allowing the user to enter just a post code and have the rest of the address auto-filled.

Similar to the US, the UK uses a system of postal codes (for example, W14 9AA). And although the Royal Mail (and others) do provide data services, supporting a database of all 27 million addresses would be a little far-reaching for my project. So, I’ll re-use a web-service provided by a 3rd party (PostcodeAnywhere)—and in doing so take advantage of their superior hardware and uptime etc.

They charge for their service, and although I don’t mind paying for walkthroughs, it would end up a little expensive if for every test suite run I incurred multiple credit charges.

So, another time when mocks run to the rescue! The key advantages to doing so are:

1. Design. It’s nice being able to specify the design of our code—one of the key benefits of mocking and test-driven development. Doing so means we’re not tied to anybody else’s API, we can do things our way!
1. Cost. It’s not plausible (nor feasible) to incur a charge everytime we run our tests—it would just make us want to run them less often.
2. Stability & Determinism. We don’t want to write a test that depends on particular data being returned from the service. Updates may change this, so, instead we’ll write the majority of our tests with well-known, stable, deterministic data.
3. Speed. Web-service lookups will be slow. Not a big problem for visitors to the site, but for our tests, not good.
4. Ability to work without an internet connection. Although I am lucky to have a shiny 24megabit connection, there are times when I may not.

Firstly, we want a test for what we’re trying to get out of our address form:

def test_can_see_postcodes  test_here  assert_tag 2 children, options for our postcodesend

Now to implement it. We’ll decouple our lookup from our controller (single-responsibility an’ all that) and have a PostcodeLookup class that lets us search for addresses. So firstly, let’s start writing a test for it.

def test_can_find_addresses_for_postcode  PostcodeLookup.find_addresses("test")end

That won’t pass just yet, so let’s put in our mock PostcodeLookup implementation, with just enough to pass the test.

Now, in our fictional land, we’ll say that the postal code “test” actually has 3 potential addresses. So let’s test that…

def testend

Finally, we want it so we can retrieve a fully populated Address when we select one of the addresses we pull back, so let’s write a test that we can do that.

def test_can_retrieve_one_address    AddressLookup.get_address(selected)  assert_equal "Line 1", address.line_1end

Excellent. Let’s go back to our functional test and run it again, success!

All we have to do now is write an implementation that supports our actual web-service. For the time-being, let’s remove our mock and put in an actual implementation in our model.

Finally we have it all working so we can put our mock back into our testing folder—and we have a fully tested postcode lookup.

If only!

I met with a friend for a quick coffee at lunch today and stopped at a cashpoint to get out some money (the Abbey cashpoint on Moorgate road for those who work in and around the City).

The joy when I read the following was massive, instantaneous, and unfortunately, very shortlived!

Flickr Pro

I’ve really started getting into digital photography now, to the point where I’m even considering going a little crazy when I have enough money to buy one of these bad boys (Canon EOS 350D).

Admittedly, so far I’ve really only taken simple one-press shots, rather than painstakingly tweaking apertures etc. to get the right look, but, it’s infectious.

A while ago I made a calendar through the nice people at PhotoBox (highly recommended by the way) for my folks as a Christmas present—it went down a storm. And, was easily one of the most fun days I’d had in the winter months in the run up to the holiday, walking around London with one of my old flatmates.

Although these images are just the ones dumped straight from my memory card, I ended up tweaking them in Photoshop for some time - ended up into the early hours the day before the deadline for Calendar orders, d’oh! - and it was a really, really interesting and rewarding experience for someone who spends most of their day with code—creative outlets are good! Incidentally, anyone else who has no idea how to use Photoshop, I can highly recommend Katrin Eismann’s Retouching & Restoring book, it single-handedly changed my opinion!

But back to Flickr, the limited account was just a little too limited, so I figured that $25 was a small price to pay for a whole lotta stuff, so I upgraded.

What’s really great is that since upgrading my Typo install I’ve also noticed the addition of filters for adding both Flickr images, and, Lightbox. Although the Typo codebase does look a tad complicated right now, I like that it’s got these kinds of things added.

So, to anyone who’s a little like I felt before (self-conscious of taking any photos and feeling like a tourist in my own City), I’d say get over it, give it a go, and Flickr-it-up there, it’s awesome fun! Now all I need is that Canon!

Pair Programming

of Microsoft recently posted about discussions of pair programming on an internal agile mailing list. We’ve just had a large team meeting at the end of the first release of our project and whilst talking through various things, pair programming seemed to be the thorniest issue we discussed. Although I originally started writing this as a comment, it soon got so big I’d figured I’d post it here instead.

The majority of the arguments against were that people felt they were more productive (and thus the team as a whole would be more productive) if people worked alone—that more lines of code were produced. Although I can see how pairing is inherently a slower process than working on your own, I still think that over the medium to long term, you end up working as quickly, but (just as important) more effectively:

1. Knowledge is spread across the team. A couple of projects I’ve been on there have been real pockets of knowledge, a real problem if people leave, or are unavailable to help. It also can impact on the work you’re doing if you can apply your knowledge from other areas of the system.
2. I personally feel much greater guilt about writing bad/untested/sloppy code when in a pair - I guess I’m quite egotistical and so want to be seen to be doing things right. This is also true of refactoring - I’m more critical of the way things are written when working as part of a pair.
3. When working to user stories (rather than very fine-grained specs), you’re less likely to make poor assumptions and end up writing irrelevant code.
4. Learning, learning, learning. I’m still a young guy (despite the grey hairs creeping in) and every minute I spend working with someone is a minute I’m learning. This is important for both technical and business reasons, picking up thoughts on OO and TDD patterns, as well as domain knowledge! To me, this point is also a big motivator, otherwise it would feel very treadmill-esque every day.

Returning to Eric’s post, I think the key thing is that its very much something people have to want to do, it can’t be forced on people.

From the experiences I’ve had I’d say that with people who want to pair it is very beneficial. Both parties share the driving, and both learn. Those who are skeptical can either feel like they’re carrying dead-weight and would be more productive alone, or find themselves just coasting through the session—with the other person being fallible for the same reasons as before: sloppy code, poor assumptions, bad testing etc. It really does need both people to question/push each other, just as one person working on their own can be fallible, so can two people who don’t question each other.

I feel very strongly that pairing has helped me improve as a developer. It’s my responsibility to be a good pairer so that the developer I’m working with sees the benefits it can bring, and see beyond overly simplistic criticisms such as fewer lines-of-code produced.

Testing ActionMailer and ActionController Interaction in Rails

In the Java and .NET world, I’ve used both jMock and NMock before for this kind of thing. Essentially we’re looking at testing interaction (rather than state as we’re testing in the existing mailer unit tests)—we’re interested in knowing that the controller asks the `ActionMailer` derived-class to try and deliver a message, what happens after that has already got unit test coverage both within my app and in Rails itself, and is of no concern to the controller. We’re testing the contract that says the mailer provides a means for the controller to send an email when a certain method is invoked. Beyond that, is not for our concern in this test. And for testing interaction we can use mocks (as I alluded to earlier in the paragraph), so anyway, on with the mocks!

Rails’ convention for mocks is to place classes in the `test/mocks/test` directory, then within the application (when in the environment is set to ‘test’) the mocks will be loaded in place of the existing classes. Inside the mock you can then add a `require ‘model/myclass’` declaration and you only need to add methods you want to redefine.

However, in my case I only need to mock it out for this test, so instead I’m going to put the class re-definition at the top of my controller’s test file.

First, the controller test, which looks as follows:

def test_email_sent_to_customer_when_order_posted  @request.session[:logged_in] = "true" end

order = Order.new(:payment_result => "open")order.customer = customers(:paul)order.save!

assert_equal false, StoreMailer.postedpost :mark_as_posted, :id => order.idassert_equal true, StoreMailer.posted

We want our mock `StoreMailer` class to include a `posted` method that returns whether the `deliver_posted_mail` method was called during the test.

So, we add the following to the top of our test file:

class StoreMailer  def self.deliver_posted_receipt(email_address, order, time)    @posted = true  endend

def self.posted  @postedend

The first time I did this I had a failure inside my controller test - since this class is used in the place of the existing `StoreMailer` in all my tests, and since other tests called the same action, `deliver_posted_receipt` was being called more than once during a test run - `@posted` was thus true when it needed to be false.

So, we add a method to reset the flag inside our mock `StoreMailer`:

def self.reset_posted    @posted = falseend

Then update our test to call `reset_posted` at the beginning of the test method. Success!

We’ve now got both the mailer covered, and, crucially that it’s being used from within the controller. Mock frameworks typically also capture information about the parameters to a method so one can verify that the correct data is being passed into the method. This would be a relatively simple thing to add, maybe I’ll go do that now :)

Anyone else have any tips to share on testing interaction between classes in Rails?

Testing ActionMailer and ActionController Interaction in Rails

In the Java and .NET world, I’ve used both jMock and NMock before for this kind of thing. Essentially we’re looking at testing interaction (rather than state as we’re testing in the existing mailer unit tests)—we’re interested in knowing that the controller asks the `ActionMailer` derived-class to try and deliver a message, what happens after that has already got unit test coverage both within my app and in Rails itself, and is of no concern to the controller. We’re testing the contract that says the mailer provides a means for the controller to send an email when a certain method is invoked. Beyond that, is not for our concern in this test. And for testing interaction we can use mocks (as I alluded to earlier in the paragraph), so anyway, on with the mocks!

Rails’ convention for mocks is to place classes in the `test/mocks/test` directory, then within the application (when in the environment is set to ‘test’) the mocks will be loaded in place of the existing classes. Inside the mock you can then add a `require ‘model/myclass’` declaration and you only need to add methods you want to redefine.

However, in my case I only need to mock it out for this test, so instead I’m going to put the class re-definition at the top of my controller’s test file.

First, the controller test, which looks as follows:

def test_email_sent_to_customer_when_order_posted  @request.session[:logged_in] = "true" end

order = Order.new(:payment_result => "open")order.customer = customers(:paul)order.save!

assert_equal false, StoreMailer.postedpost :mark_as_posted, :id => order.idassert_equal true, StoreMailer.posted

We want our mock `StoreMailer` class to include a `posted` method that returns whether the `deliver_posted_mail` method was called during the test.

So, we add the following to the top of our test file:

class StoreMailer  def self.deliver_posted_receipt(email_address, order, time)    @posted = true  endend

def self.posted  @postedend

The first time I did this I had a failure inside my controller test - since this class is used in the place of the existing `StoreMailer` in all my tests, and since other tests called the same action, `deliver_posted_receipt` was being called more than once during a test run - `@posted` was thus true when it needed to be false.

So, we add a method to reset the flag inside our mock `StoreMailer`:

def self.reset_posted    @posted = falseend

Then update our test to call `reset_posted` at the beginning of the test method. Success!

We’ve now got both the mailer covered, and, crucially that it’s being used from within the controller. Mock frameworks typically also capture information about the parameters to a method so one can verify that the correct data is being passed into the method. This would be a relatively simple thing to add, maybe I’ll go do that now :)

Anyone else have any tips to share on testing interaction between classes in Rails?