Wednesday, May 21, 2008

Assumptions

So, I was writing a few RSpec tests today, and required Hpricot to look at a few views. This was the code I wrote:
     links.each do |link|
this_taxa_name = nil # scope
img = link.at("img")
if img.nil?
this_taxa_name = link.inner_text # This was the text link
else
has_image = true # This is the image.
this_taxa_name = img['alt']
end
taxa_name ||= this_taxa_name
assert_equal taxa_name, this_taxa_name, 'The names for the featured species were inconsistent (image alt/text)'
taxa_link ||= link['href']
assert_equal taxa_link, link['href'], 'The links for the featured species were inconsistent (image/text)'
end
assert has_image, 'There was no image for the featured species'

...This was all because I was trying NOT to assume that the image always precedes the text for the image. The test ended up being a bit longer than one page, so I asked a co-worker to look at it. His simple suggestion was "it's okay to assume the image comes before the text". By making that assumption, this block of code above becomes:
      assert !(links.nil? or links.length == 0), 'The featured species had no links'
assert_not_nil links[0].at('img'), 'There was no image for the featured species'
assert_equal links[0]['href'], links[1]['href'], 'The links for the featured species were inconsistent (image/text)'
assert_equal links[0].at('img')['alt'], links[1].inner_text, 'The names for the featured species were inconsistent (image
It's very easy to see why assumptions are the #1 problem that developers have. They make life much, MUCH easier.

I suppose that's true of life as well.

No comments: