scalaspecs2

Specs2 unit specification referencing


I've got the following spec:

import org.specs2.mutable.{After, Specification}
import org.specs2.specification.Scope
import org.specs2.specification.core.{Fragment, Fragments}

class TestRefSpec extends Specification {

  "My Spec" >> new iii {
    xxx(i)
  }

  def xxx(i: Int) = {
    def e1 = {
      println(s"** $i > 0")
      i must be_>(0)
    }
    def e2 = {
      println(s"** $i < 100")
      i must be_<(100)
    }

    "i should be > 0" >> { e1 } 
    "and < 100" >> { e2 }
  }

}

trait iii extends Scope with After {
  val i = 142

  def after = println("finalising")
}

The idea is that there is a spec that tests behaviours of something and then there are the target(s) represented by the Scope(s) that the behaviours are tested for. Ideally the behaviours would sit in a separate trait. Alas when I run it though the output I'm getting is as follows:

[info] TestRefSpec
[info] + My Spec
[info] Total for specification TestRefSpec
[info] Finished in 560 ms
[info] 1 example, 0 failure, 0 error

Which means the tests do not really run.

Does anyone know how do I actually achieve what I'm intending to?

Thanks in advance!


Solution

  • I think the problem is that you are wrapping xxx(i) method call in a new iii {}.

    This can't work, as the code inside the curlies is executed in the constructor of the new anonymous class extending iii and the result of the whole expression is a subtype of the iii, not Fragments, so the internal structure of examples, you construct and return from inside of xxx() method, can't make it to the specs2 >> operator. Normally only the individual examples are - preceded by specs2 in operator are wrapped in a scope.

    This will work:

    class TestRefSpec extends Specification {
    
      "My Spec" >> {
        xxx(42)
      }
    
      def xxx(i: Int) = {
        def e1 = {
          println(s"** $i > 0")
          i must be_>(0)
        }
        def e2 = {
          println(s"** $i < 100")
          i must be_<(100)
        }
    
        "i should be > 0" in new iii { e1 }
        "and < 100" in new iii { e2 }
      }
    
    }