Search code examples
scalaspecs2

How to access test/example name in Specs2?


I have some tests that share a fixture and would like to isolate the tests from each other. One way to do this would be to use the test/example name as part of a 'namespace' (eg as part of a directory path).

How can the test/example name be accessed within itself?

For example:

class MySpec extends Specification {
  "Something" should {
    "do something" in {
      // access String "do something"
    }

    "do something else" in {
      // access String "do something else"
    }
  }
}

Solution

  • So you can do this two ways:

    Specs2 allows you to use a string as an optional parameter to your Fragments so you can do something like this:

    class MySpec extends Specification {
      "Something" should {
        "do something" in {
          fragmentName: String =>
            println(fragmentName) //prints do something
            ok
        }
    
        "do something else" in {
          fragmentName: String =>
            println(fragmentName) //prints do something else
            ok
        }
      }
    }
    

    There's also the hacky way (I played with this one first and just couldn't throw it away): UPDATED Here's a 'better' hacky version suggested by @Eric

    class MySpec extends Specification {
      "Something" should {
        "do something" in {
          val fragmentName = is.examples(0).desc
          println(fragmentName) //prints do something
          ok
        }
    
        "do something else" in {
          val fragmentName = is.examples(1).desc
          println(fragmentName) //prints do something else
          ok
        }
      }
    }