我注意到用Play / specs2设置每个测试需要花费很多时间。我知道您可以创建一个扩展mutable.Before
的特征并使用它来设置测试,但在那里创建的任何值似乎都超出了我的测试范围。
我希望能够做的是在每个测试运行之前在类或特征中设置val user = User.create("User Name")
,以便稍后我可以在测试中访问user
。如何实现这一目标?
// SpecificationWithFixtures.scala
package models
import org.specs2.execute.{AsResult, Result}
import org.specs2.mutable._
import play.api.test.Helpers._
import play.api.test._
abstract class SpecificationWithFixtures extends Specification {
abstract class WithFakeDB extends WithApplication(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
override def around[T: AsResult](t: => T): Result = super.around {
t
}
}
}
// UserSpec.scala
package models
import org.junit.runner._
import org.specs2.runner._
@RunWith(classOf[JUnitRunner])
class UserSpec extends SpecificationWithFixtures {
"User.create" should {
"save user in the database" in new WithFakeDB {
val user = User.create("User Name")
// Some test for user
}
}
"User.findAll" should {
"return a list of all users" in new WithFakeDB {
val user = User.create("User Name")
// Another test for user
}
}
}
答案 0 :(得分:1)
你可以做的是:
def withUser[T](test: User => T): T = test(User create "Username")
// or even more configurable
def withUser[T](name: String)(test: User => T): T = test(User create name)
// Then writing expectations you can do
"User Roger" in withUser("Roger") {
roger => // trivial example
roger.name must_== "Roger"
}
// or even
"User" in withUser("John") {
_.name must_== "John"
}
这种贷款模式很有用,可以编写规范2.
在前面的示例中,用户每次期望(in
),但它可以用于一组期望(should
,>>
),或者用于所有人。
"User" should withUser("xyz") {
"exp1" in { ??? }
}