Monday, September 20, 2010

Getting over assert_difference

For quite a while now I have been using assert_difference or its close cousin from shoulda should_change. When I recently updated to a recent version of shoulda I noticed that they had deprecated should_change. The note in the shoulda documentation says the following: "This macro was deprecated because these tests aren’t as valuable as alternative tests that explicitly test the final state."

Ok, now what to do? assert_change is super easy to use, but does it really ensure that the desired action is actually happening? For example:

This example test asserts that the number of User objects in the database has increased by 1. No real guarantee that it was actually the User object we were interested in creating.

Lately I have been trying to be a little more explicit about what is actually happening. It is taking a little while to get used to doing things this way but the results have been satisfying. Here is an example:

This example test asserts that a User object is getting assigned to the @user instance variable and that User object is no longer a new record.

Wednesday, September 8, 2010

Code Readability: Quick, Millions or Billions?


It is really easy to get the order of magnitude wrong on a number in code. I had settled into the habit of carefully counting my digits to make sure it was right until one of my co-workers pointed out a neat feature of ruby.

Ruby allows underscores to be inserted into numbers between any two digits. The underscores are purely cosmetic and do not affect the value of the number. This feature allows a developer to use underscores as an accountant might use commas.

3193490646      # standard representation of a number in ruby
3_193_490_646   # same value, much more readable

One less excuse for order of magnitude errors when using ruby.

A little looking around did not find any similar functionality in other languages, I checked into C/C++, Smalltalk, Python, Perl, PHP, Java, Javascript, Lisp, and Erlang. I am very curious to know if anyone knows of another language or particular implementation of one of the listed languages that supports similar functionality.

Thanks to Dallas Reedy for introducing me to this awesome feature of Ruby