Wednesday, July 18, 2007

Mocha

So my previous post talked about overriding delegation. Then I remembered, Mocha. An honest to goodness stubbing/mocking library. Rather obviously, when testing units, I really don't want to fiddle around with the interaction of objects in each and every instance.

So instead of my convoluted example of conditionally_overriding_delegation, I can do the following (but hey you may have already known this):


class AbstractUnit
extend Forwardable
def_delegate :foo, :name

def has_name?
!(name.nil? || name.blank?)
end
end

class AbstractUnitTest < Test::Unit::TestCase
def setup
@object = AbstractUnit.new
end

# Perhaps a reasonable test for delegation?
def test_should_delegate_name_to_foo
assert_equal @object.name, @object.foo.name
end

def test_has_name_should_be_false_if_name_is_empty
@object.stubs(:name).returns('')
assert ! @object.has_name?
end

def test_has_name_should_be_false_if_name_is_nil
@object.stubs(:name).returns(nil)
assert ! @object.has_name?
end

def test_has_name_should_be_false_if_name_is_blank
@object.stubs(:name).returns('hello world')
assert @object.has_name?
end

end


Even in this case, Mocha is rather useful, I don't have to worry about testing the coupling that occurs due to delegation, and can test the objects responsibilities. Of course, now its time to look more into Mocha's documentation. It looks like there is some rather amazing stuff that can be done.

No comments: