Wednesday, December 16, 2009

Specs BDD Testing framework

This is the second Scala test framework topic and focuses on the excellent Specs framework. The other topic was on ScalaTest, another excellent testing framework for Scala.

Specs is focussed on BDD testing (Behaviour Driven Design) and is the inspiration for ScalaTests WordSpec. From what I understand Specs was in-turn inspired by RSpec the Ruby BDD testing framework.

Specs has some truly unique features to it which we will encounter in future topics. But for now just the basics. The following example tests a couple of Scala's XML support in order to demonstract the general pattern followed when writing Specs' tests.

  1. # scala -classpath ~/.m2/repository/org/scala-tools/testing/specs/1.6.1/specs-1.6.1.jar
  2. scala> import org.specs._
  3. import org.specs._
  4. scala> object XmlSpec extends Specification {
  5.      |  val sample = <library>
  6.      |         <videos>
  7.      |         <video type="dvd">Seven</video>
  8.      |         <video type="blue-ray">The fifth element</video>
  9.      |         <video type="hardcover">Gardens of the moon</video>
  10.      |         </videos>
  11.      |         <books>
  12.      |         <book type="softcover">Memories of Ice</book>
  13.      |         </books>
  14.      |         </library>
  15.      |  "Scala XML" should {
  16.      |   "allow xpath-like selection" in {
  17.      |    (sample \\ "video").size must be (3)    
  18.      |   }
  19.      |   "select child nodes" in {
  20.      |    // This test fails because child is a sequence not a string
  21.      |    // See the results of the tests
  22.      |    sample.child must contain (<videos/>)
  23.      |   }
  24.      |  }
  25.      |  }
  26. defined module XmlSpec
  27. scala> XmlSpec.main(Array[String]())
  28. Specification "XmlSpec"
  29.   Scala XML should
  30.   + allow xpath-like selection
  31.   x select child nodes <-- x indicates failure.
  32.     'ArrayBuffer(
  33.                    , <videos>
  34.                    <video type="dvd">Seven</video>
  35.                    <video type="blue-ray">The fifth element</video>
  36.                    <video type="hardcover">Gardens of the moon</video>
  37.                    </videos>, 
  38.                    , <books>
  39.                    <book type="softcover">Memories of Ice</book>
  40.                    </books>, 
  41.                    )' doesn't contain '<videos></videos>' (< console>:24)
  42. Total for specification "XmlSpec":
  43. Finished in 0 second, 52 ms
  44. 2 examples, 2 expectations, 1 failure, 0 error

1 comment: