In the behavior-driven development style, you specify the behavior of the code with text and verify that behavior with tests.
ScalaTest has three traits that facilitate this style: Spec, WordSpec, and FlatSpec. Although three traits
all facilitate BDD, they differ in the way they let you express the specification text.
Note: Trait FeatureSpec can also be considered a behavior-driven development style
but it is geared more for functional, integration, or acceptance testing, less for unit testing.
Trait Spec is inspired in part by Ruby's RSpec. You express the specification text in nested describe and it clauses.
Here's an example:
import org.scalatest.Spec import org.scalatest.matchers.ShouldMatchers import scala.collection.mutable.Stack class StackSpec extends Spec with ShouldMatchers { describe("A Stack") { describe("(when empty)") { val stack = new Stack[Int] it("should be empty") { stack should be ('empty) } it("should complain when popped") { evaluating { stack.pop() } should produce [NoSuchElementException] } } } }
To get started writing Specs, see:
Trait WordSpec is inspired in part by Eric Torreborre's specs. You express the specification text by placing words after strings. Here's an example:
import org.scalatest.WordSpec import org.scalatest.matchers.ShouldMatchers import scala.collection.mutable.Stack class StackSpec extends WordSpec with ShouldMatchers { "A Stack" when { "empty" should { val stack = new Stack[Int] "be empty" in { stack should be ('empty) } "complain when popped" in { evaluating { stack.pop() } should produce [NoSuchElementException] } } } }
To get started writing WordSpecs, see:
Trait FlatSpec differs from the other BDD traits in that it avoids nesting. The "Flat" in FlatSpec refers to the fact that the
specification text lines up flat against the left column, with no nesting. Here's an example:
import org.scalatest.FlatSpec import org.scalatest.matchers.ShouldMatchers import scala.collection.mutable.Stack class StackSpec extends FlatSpec with ShouldMatchers { val stack = new Stack[Int] "A Stack (when empty)" should "be empty" in { stack should be ('empty) } it should "complain when popped" in { evaluating { stack.pop() } should produce [NoSuchElementException] } }
To get started writing FlatSpecs, see:
ScalaTest is brought to you by Bill Venners, with contributions from several other folks. It is sponsored by Artima, Inc.
ScalaTest is free, open-source software released under the Apache 2.0 license.
Copyright © 2009 Artima, Inc. All Rights Reserved.