6

给定如下代码:

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”之前/之后执行相同的代码之前和之后,即使测试本身失败,“之后”方法也应该执行?

4

2 回答 2

3

如果您使用 Given/When/Then 步骤,您可以使用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
  }
}

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

PS:pp是一种实用方法,喜欢println在执行期间在终端中显示一些东西。优于 println 的优点是它返回其参数,因此您可以编写1.pp must_== 1

于 2013-01-13T01:14:30.330 回答
2

看看文档:http ://etorreborre.github.com/specs2/guide/org.specs2.guide.Structure.html#Before/After

于 2013-01-12T16:00:08.877 回答