2013-04-18 48 views

回答

0

這可能會工作:

class MySpec extends Specification with BeforeAfterExample { 
    var currentExample = 0 
    var testName = "" 
    var clientDir:File = null 

    def before { 
    testName = is.examples(currentExample).desc.toString.replaceAll(" ", "-") 
    clientDir = new File(workspaceRoot, testName) 
    clientDir.mkdirs() 
    } 

    def after { 
    FileUtils.deleteDirectory(clientDir) 
    currentExample += 1  
    } 
} 

我不認爲你可以在之前和之後沒有做那種事情的方法得到太多的上下文像這樣哈克。

+0

由於規格的副本每個例如由,這是行不通的。 OTOH,你的回答有助於我提供更多關於specs2如何工作的背景信息。我可以創建並銷燬beforeSpec和afterSpec中的目錄。 –

0

你可以做你想做的使用specs2 ExampleFactory

import org.specs2._ 
import specification._ 

class TestSpec extends Specification { def is = 
    "test" ! { 
    ok 
    } 
    case class BeforeAfterExample(e: Example) extends BeforeAfter { 
    def before = println("before "+e.desc) 
    def after = println("after "+e.desc) 
    } 
    override def exampleFactory = new ExampleFactory { 
    def newExample(e: Example) = { 
     val context = BeforeAfterExample(e) 
     e.copy(body =() => context(e.body())) 
    } 
    } 
} 

API的這部分最近纔打開,這只是在1.15快照對於現在可用(您可以解決此限制使用最近的specs2版本通過在org.specs2開始的包中直接創建您的工廠)。

0

有點哈克,但這對我的作品:

/** 
* Returns the name of the currently executing example 
*/ 
def getCurrentExampleName(spec: Specification): String = { 

    val stack = new Exception().getStackTrace 
    val specLinesUpStack = for (
    line <- stack 
     if line.getClassName.startsWith(spec.getClass.getName)) 
     yield line.getLineNumber 

    spec.is.examples 
    .find(e => specLinesUpStack.contains(e.location.lineNumber)) 
    .get 
    .desc.toString() 
} 
相關問題