Search code examples
unit-testingscalaspecs2

Running an individual test from a specification


Is there a way to run a specific test from a Specs 2 Specification? e.g. If I have the following:

class FooSpec extends Specification {
  "foo" should {
    "bar" in {
      // ...
    }

    "baz" in {
      // ...
    }
  }
}

I would like to have a way to run only FooSpec > "foo" > "bar" (using some arbitrary notation here).


Solution

  • You can use the ex argument from sbt to run a specific example:

    sbt> test-only *FooSpec* -- ex bar
    

    You can also mix-in the org.specs2.mutable.Tags trait and include a specific tag:

    sbt> test-only *FooSpec* -- include investigate
    
    class FooSpec extends Specification with Tags {
      "foo" should {
        tag("investigate")
        "bar" in {
          // ...
        }
        "baz" in {
           // ...
         }
       }
    }
    

    You can also just re-run the previously failed examples, whatever they are

    sbt> test-only *FooSpec* -- was x
    

    Finally, in the next 2.0 release (or using the latest 1.15-SNAPSHOT), you will be able to create a script.Specification and use "auto-numbered example groups":

    import specification._
    
    /**
     * This kind of specification has a strict separation between the text 
     * and the example code
     */ 
    class FooSpec extends script.Specification with Groups { def is = s2"""
      This is a specification for FOO
    
      First of all, it must do foo
      + with bar
      + with baz
    
      """ 
    
      "foo" - new group {
        eg := "bar" must beOk
        eg := "baz" must beOk
      }
    }
    
    // execute all the examples in the first group
    sbt> test-only *FooSpec* -- include g1
    
    // execute the first example in the first group
    sbt> test-only *FooSpec* -- include g1.e1
    

    There is however no way to specify, with a mutable Specification, that you want to run the example "foo" / "bar". This might be a feature to add in the future.