Question

I am trying to run some tests in Scala using specs2, but I am having some problems with some test cases not being executed.

Here is a minimal example to illustrate my problem.

BaseSpec.scala

package foo

import org.specs2.mutable._

trait BaseSpec extends Specification {
  println("global init")
  trait BeforeAfterScope extends BeforeAfter {
    def before = println("before")
    def after = println("after")
  }
}

FooSpec.scala

package foo

import org.specs2.mutable._

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in new BeforeAfterScope {
      "should fail" in {
        true must beFalse
      }
    }
  }
}

I would expect the test to fail, however it seems that the case "should fail" in the nested in statement does not get executed.

If I remove either the nested in statement or the BeforeAfterScope, the test behaves correctly so I guess I am missing something, but I did not manage to find this out in the documentation.

[EDIT]

In my use case, I am currently populating the database in the before method and cleaning it up in the after method. However, I would like to be able to have several test cases without cleaning up and populating the database again between each. What would be the right way to do this?

Was it helpful?

Solution

The Scope must be created exactly where you create your example:

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in {
      "should fail" in new BeforeAfterScope {
        true must beFalse
      }
    }
  }
}

[UPDATE: 10-12-2015 for specs2 3.x]

Note that if you don't need to inherit values from the BeforeAfterScope trait, it is actually simpler to have the BaseSpec extend org.specs2.specification.BeforeAfterEach and define the before and after method there.

If, on the other hand, you want to do some setup/teardown before and after all your examples you need the BeforeAfterAll trait. Here is a specification using both traits:

import org.specs2.specification.{BeforeAfterAll, BeforeAfterEach}

trait BaseSpec extends Specification with BeforeAfterAll with BeforeAfterEach {
  def beforeAll = println("before all examples")
  def afterAll = println("after all examples")

  def before = println("before each example")
  def after = println("after each example")
}

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in {
      "should fail" in {
        true must beFalse
      }
    }
  }
}

This approach is documented here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top