Testing Codes

Another notes after reading “Object-Oriented Design in Ruby”, regarding testing section.

Changeability is one important design metric, and appropriate testing code asissts them through performing refactoring or avoiding unexpected regression. But, too much testing code can increase costs to maintain or change the testing code itself. Therefore, “What should be tested” and “What should NOT be tested” needs to be carefully designed. But there’re not definitive answers for that, and it’s rather a design decision. In practice, most programmers tend to write too many tests.

The followings are some examples that should not be tested.

[Private Methods]
Tests should concentrate on the incoming or outgoing messages that cross an object’s boundaries. Test for private methods are redundant and unstable, which both increases the costs for maintenances.

[Query Methods]
Outgoing messages that just gets information from the receiver with no side-effect is called query methods, and should not be tested by the sending object. It’s part of the receiver’s public interface, and testing in both sides duplicates the testing codes.

In the book, MiniTest was used for showing examples. One example was to use Modules for sharing testing. “RSpec” seems to have similar concept through shared_examples statement as follows. It’s nice.

require 'rspec'

class Mechanic
  def prepare_trip
    "prepare bicycle..."
  end
end

class Driver
  def prepare_trip
    "prepare vehicle..."
  end
end

shared_examples_for "trip" do
  it "should respond to prepare_trip" do
    subject.should respond_to(:prepare_trip)
    subject.prepare_trip.should_not be_nil
  end
end

describe 'Mechanic' do
  let(:mechanic) { Mechanic.new }
  include_examples "trip" do  # with parameter
    let(:subject) { mechanic }
  end
end

describe 'Driver' do
  let(:subject) { Driver.new }
  include_examples "trip"  # without parameter
end
Advertisements

Posted on February 16, 2013, in Ruby. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: