2014-05-12 64 views
0

我試圖編寫一個可變的Spec,它有一個由Scope傳入的值。每次測試運行後,我還需要做一些清理工作。按照文檔,我嘗試使用Outside加上After,但得到了不同的結果。Specs2:在外部使用後

第五個例子是正確的方法,還是我缺少一些基本的東西?

import org.specs2.mutable.{After, Specification} 
import org.specs2.specification.Outside 

class ExampleSpec extends Specification { 
    "Tests using Outside and After" >> { 
    "#1 doesn't run the after" in c1() { 
     (m: String) => { 
     println("Running test 1.") 
     success 
     } 
    } 
    "#2 doesn't actually run the test" in new c2() { 
     (m: String) => { 
     println("Running test 2.") 
     failure 
     } 
    } 
    "#3 doesn't run the after" in (new t3{}) { 
     (m: String) => { 
     println("Running test 3.") 
     success 
     } 
    } 
    "#4 doesn't actually run the test" in new t4 { 
     (m: String) => { 
     println("Running test 4.") 
     failure 
     } 
    } 
    "#5 works, but is it the right way?" in new t5 { 
     val sessionKey = outside // The test would have to call outside? 
     println("Running test 5.") 
     success 
    } 
    } 

    trait common extends Outside[String] with After { 
    def name: String 
    def outside = "Used by the real test." 
    def after = println("After for " + name) 
    } 
    case class c1() extends common { def name = "c1" } 
    case class c2() extends common { def name = "c2" } 
    trait t3 extends common { def name = "t3" } 
    trait t4 extends common { def name = "t4" } 
    trait t5 extends common { def name = "t5" } 
} 

這給出了以下的輸出:

Running test 1. 
After for c2 
Running test 3. 
After for t4 
Running test 5. 
After for t5 
[info] ExampleSpec 
[info] 
[info] Tests using Outside and After 
[info] + #1 doesn't run the after 
[info] + #2 doesn't actually run the test 
[info] + #3 doesn't run the after 
[info] + #4 doesn't actually run the test 
[info] + #5 works, but is it the right way? 
[info] 
[info] Total for specification ExampleSpec 
[info] Finished in 19 ms 
[info] 5 examples, 0 failure, 0 error 

注:每Eric的評論Question 21154941,我知道測試1和2是不正確的做法。我把它們放在這裏是詳盡無遺的,因爲在其他時候,你可以使用case類來進行上下文/變量隔離。

回答

0

你的情況做最簡單的事情就是使用org.specs2.specification.FixtureExample特點:

class ExampleSpec extends Specification with FixtureExample[F] { 
    "Tests using a fixture" >> { 
    "you can use the fixture values" in { f: F => 
     println("Running test 1 with "+f.sessionKey) 
     success 
    } 
    "there is cleanup after each example" in { f: F => 
     success 
    } 
    } 

    def fixture[R : AsResult](f: F => R): Result = { 
    try AsResult(f(F())) 
    finally cleanup 
    } 

    def cleanup = println("cleanup") 
} 

case class F(sessionKey: String = "key") 
+0

謝謝,埃裏克。這應該讓我走上正軌。 –