Scala specs2嵌入了上下文

Dan*_*rez 2 scala specs2

我正在尝试使用specs2在Scala中运行一些测试,但是我遇到了一些未执行的测试用例的问题.

这是一个简单的例子来说明我的问题.

BaseSpec.scala

package foo

import org.specs2.mutable._

trait BaseSpec extends Specification {
  println("global init")
  trait BeforeAfterScope extends BeforeAfter {
    def before = println("before")
    def after = println("after")
  }
}
Run Code Online (Sandbox Code Playgroud)

FooSpec.scala

package foo

import org.specs2.mutable._

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in new BeforeAfterScope {
      "should fail" in {
        true must beFalse
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望测试失败,但似乎嵌套in语句中的"应该失败"的情况不会被执行.

如果我删除嵌套in语句或者BeforeAfterScope,测试行为正确,所以我想我错过了一些东西,但我没有设法在文档中找到它.

[编辑]

在我的用例中,我目前正在填充before方法中的数据库并在方法中清理它after.但是,我希望能够在没有清理的情况下拥有多个测试用例,并在每个测试用例之间重新填充数据库.这样做的正确方法是什么?

Eri*_*ric 10

必须在创建示例的位置创建范围:

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in {
      "should fail" in new BeforeAfterScope {
        true must beFalse
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

[更新:10-12-2015 for specs2 3.x]

请注意,如果您不需要从BeforeAfterScope特征继承值,那么实现BaseSpec扩展org.specs2.specification.BeforeAfterEach并在那里定义beforeafter方法实际上更简单.

另一方面,如果您想在所有示例之前和之后进行一些设置/拆卸,则需要BeforeAfterAll特性.这是一个使用两个特征的规范:

import org.specs2.specification.{BeforeAfterAll, BeforeAfterEach}

trait BaseSpec extends Specification with BeforeAfterAll with BeforeAfterEach {
  def beforeAll = println("before all examples")
  def afterAll = println("after all examples")

  def before = println("before each example")
  def after = println("after each example")
}

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in {
      "should fail" in {
        true must beFalse
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方法记录在这里.