Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Friday, July 10, 2009

metric_fu, rcov, and rspec

I've been setting up metric_fu on one of my projects, and I ran into a problem where the rcov report was not including my specs. (This is an old project that has both Test::Unit tests and RSpec specs.) I did lots and lots of digging, and was baffled that no one has mentioned that they cannot run coverage reports for their specs using metric_fu. It seemed like an obvious and heinous oversight on the part of metric_fu.

As always, I suspected that I was missing something. Test::Unit tests can be run individually from the command line like ruby path/to/test, and metric_fu appeared to be trying to do this with the specs, but when I did ruby path/to/spec I got nothing.

I actually looked at the metric_fu specs to discover this, and it is probably very obvious to any serious RSpec user, but I discovered that I needed to add require "spec/autorun" to the top of my spec_helper.rb file. This includes the magic that makes ruby path/to/spec work, and makes rcov include my specs in its report when it is invoked by metric_fu.

Friday, February 13, 2009

To 'and' or not to 'and'

Ruby has two 'or' operators ('||' and 'or'). It also has two 'and' operators ('&&' and 'and'). This can be confusing to people, but especially to those learning the language. There is a temptation to use 'and' and 'or' because it is more readable, and I can certainly appreciate that. However, there are some serious differences between these operators, and I recommend only using '&&' and '||' in boolean expressions.

Of the two, 'and' has lower precedence than '&&', and it is the same with 'or' and '||'. This means that there is a difference between:

irb(main):001:0> true || false && false
=> true

and:

irb(main):002:0> false || true and false
=> false

You might then be tempted to just adopt the practice of always using 'or' and 'and', but that also might surprise you:

irb(main):023:0> true or false and false
=> false

This surprising result follows from the fact that, whereas '&&' has a higher precedence than '||', 'or' has the same precedence as 'and', so Ruby just evaluates the statement left to right handling first the 'or' then the 'and'.

Even though you may understand the nuances between these operators, not everyone may understand, and the fact is that 99% of programmers in the world (really 100% I would hope) can understand statements involving '&&' and '||'. So let's just stick with the traditional boolean operators, because in the end it is actually more readable.