Thursday, May 10, 2012

Data Driven Unit Test

How do you avoid loops in your specs?

Like Alex points out, this is a test smell according to Gerard Mezos. In .NET they have something called as data driven unit test. In Ruby we can accomplish the same thing using the following:

  def data_driven_spec(container)
    container.each do |element|

and in your test you can do :

  it "should return back slash pre-pended to all special characters" do
    SPECIAL_CHARACTERS = ["?", "^", "$", "/", "\\", "[", "]", "{", "}", "(", ")", "+", "*", "." ]
    data_driven_spec(SPECIAL_CHARACTERS) do |special_character|
      result = Regexpgen::Component.match_this_character(special_character)
      result.should == "\\#{special_character}"    

The code is taken from my regexpgen ruby gem. My test differs from the message that goes in to the it method. I have raised the level of abstraction, whereas Alex substitues the a variable to vary the message.