The Ruby 2.5.0 feature nobody talks about

We have branch coverage now, and that’s great!

Background

Line coverage

# hello.rb (with line numbers)1: def hello(number)
2: if number == 1
3: 'world'
4: else
5: 'mars'
6: end
7: end
8:
9: hello(1)
Coverage.start
load 'hello.rb'
puts Coverage.result
{"hello.rb"=>[1, 1, 1, nil, 0, nil, nil, nil, 1]}
Y -> 1: def hello(number)
Y -> 2: if number == 1
Y -> 3: 'world'
Y -> 4: else
N -> 5: 'mars'
Y -> 6: end
Y -> 7: end
Y -> 8:
Y -> 9: hello(1)
# hello.rb1: def hello(number)
2: (number == 1) ? 'world' : 'mars'
3: end
4:
5: hello(1)
Y-> 1: def hello(number)
Y-> 2: (number == 1) ? 'world' : 'mars'
Y-> 3: end
Y-> 4:
Y-> 5: hello(1)

Branch coverage

Coverage.start(branches: true)
load 'hello.rb'
puts Coverage.result
"hello.rb"=> {
:branches=> {
[:if, 0, 2, 2, 2, 34]=> {
[:then, 1, 2, 18, 2, 25]=>1,
[:else, 2, 2, 28, 2, 34]=>0
}
}
}
[clause, id, row_start, col_start, row_end, col_end] => covered 

The hidden branch

# hello.rb (with line numbers)1: def hello(number)
2: if number == 1
3: 'world'
4: end
5: end
6:
7: hello(1)
hello(1) # returns “world”
hello(2) # returns nil
"hello.rb=> {
:branches=> {
[:if, 0, 2, 2, 4, 5]=> {
[:then, 1, 3, 4, 3, 11]=>1,
[:else, 2, 2, 2, 4, 5]=>0
}
}
}

Conclusions

Open Source Software Engineer at Renuo AG. Located in Zürich. I do stuff. Sometimes.