2013-01-12 50 views
6

鉴于类似的代码:Specs2和@前/ @之后,类似的方法

class RESTAcceptanceTest extends Specification { 

    override def is = anonymous^signinOAuth 

    def anonymous = "Something"  ^givenSomething^
        "must happen" ^mustHappen 
    end 

    def signinOAuth = "Signin"    ^givenSignin^
        "works as expected" ^userExistsInDatabase 
    end 

    // rest of object definitions 

} 

我怎么保证之前,执行代码之后同前/ 后“匿名” “signinOAuth” ,即使测试本身失败,“after”方法应该执行 ?

回答

3

如果您正在使用鉴于/时/然后步骤,你可以使用一个Context控制什么获取之前执行和每个示例后:

import org.specs2._ 
import specification._ 

class MySpec extends Specification { def is = 
    "anonymous"^
    "something"^something^
    "must happen"^mustHappen^endp^ 
    "OAuth"^ 
    "signing"^signing^
    "works ok"^worksOk 

    lazy val something: Given[Int] = (s: String) => { s.pp; 1 } 
    lazy val mustHappen: Then[Int] = (i: Int) => (s: String) => 
    context { s.pp; i must_== 1  } 

    lazy val signing: Given[Int] = (s: String) => { s.pp; 2 } 
    lazy val worksOk: Then[Int] = (i: Int) => (s: String) => 
    context { s.pp; i must_== 2 } 

    lazy val context = new BeforeAfter { 
    def before = "before".pp 
    def after = "after".pp 
    } 
} 

在上面的代码中,使用context对象的apply方法将代码包装为使用beforeafter执行。另外,如果您向其中一个示例添加错误,您将看到“after”代码始终执行。

PS:pp是一种实用方法,如println在执行期间在终端中显示某些内容。优于println的是它返回它的参数,所以你可以写1.pp must_== 1

+0

谢谢!我几乎这样做,但没有找到如何处理上下文。我希望用这个例子更新Specs2用户指南。 – jdevelop

+3

我已经更新了文档,但也启用了使用'BeforeExample','AfterExample',...特征与给定/当/然后步骤(1.12.4-SNAPSHOT for Scala 2.9.2和1.13.1-SNAPSHOT对于Scala 2.10)。请参阅文档:http://etorreborre.github.com/specs2/guide-SNAPSHOT/guide/org.specs2.guide.Structure.html#Contexts。 – Eric