Fork me on GitHub

Snippets #87

Asserting Floats with assert_in_delta

While asserting some results of numeric conversions in a Rails application, I came across a little problem in running my unit tests. When I tried to use assert_equals to test that a method that returned a float, my expected value and actual value for the assertion were different, even though they looked the same.

Some digging later and it's revealed that although the values look similar, they are in fact different. At first I used the round method for my floats so that they were exactly the same. It fixes the problem I had with my assertion by ensuring that both values are rounded to the same number, but I didn't like the idea of changing actual values in my tests.

A better way of testing this is to use assert_in_delta. This assertion will indicate if two values are equal within a certain tolerance range. The best way to see it in action is using a few examples.

When you're working with floats, you might be using numbers that you don't initially know they're length as they are the result of calculations. If you're not required to round the numbers off but you still need to test the results of a calculation, assert_in_delta is a better way of testing your calculation code, rather than formatting numbers to specific sizes.

Snippets #82

Snippets #67

Let's ease into the New Year with a couple of my favourites from the last week:

  1. The Rails 3 Router: Rack it Up - An overview of the changes in the new router. Really looking forward to the release of Rails 3.
  2. history: ruby integration testing - It seems that every year there are more and more options for integration testing. I wonder how many 2010 will offer?

Snippets #65

  1. Subdomains and sessions to the rescue - A detailed look at adding subdomains (including testing!) to your Rails app.
  2. Protip: Passing parameters to your Rake tasks - I so need this for a Sinatra app I'm working on!
  3. Your pages will load faster with Rails! - Some tips on getting faster page loads.