使用Specs2播放FakeRequest会记住跨测试的请求

时间:2013-08-03 22:32:30

标签: scala playframework-2.0 specs2

我有一个小型Play(2.1.2)应用程序,它试图存储一些数据并执行重定向。我有2个规格:

"save the user" in {
  running(FakeApplication()) {
    val Some(create) = route(
      FakeRequest(PUT, "/users")
        .withSession(("user-id", user_id))
        .withFormUrlEncodedBody(("username", any_username))
    )

    status(create) must equalTo(SEE_OTHER)
    redirectLocation(create).map(_ must equalTo("/profile")) getOrElse failure("missing redirect location")
  }
}

"display errors with missing username" in {
  running(FakeApplication()) {
    val Some(create) = route(
      FakeRequest(PUT, "/users")
        .withSession(("user-id", user_id))
    )

    status(create) must equalTo(BAD_REQUEST)
    contentAsString(create) must contain ("This field is required")
  }
}

当我运行这些测试时,第二个测试的结果与第一个测试的结果相同,因此SEE_OTHER代替BAD_REQUEST。当我改变测试的顺序时,两者都可以正常工作。当我删除第一个时,第二个也会通过。

Scala / Play / Specs2是否会以某种方式记住测试或请求中的状态?我需要做些什么才能确保它们孤立地运行?

编辑:

我的控制器中的代码如下所示:

val form: Form[User] = Form(
  mapping(
    "username" -> nonEmptyText
  )(user => User(username))(user=> Some(user.username))
)

form.bindFromRequest.fold(
  errors => BadRequest(views.html.signup(errors)),
  user => Redirect("/profile")
)

1 个答案:

答案 0 :(得分:1)

Playframework 2 / Specs2不会在测试之间保持状态,除非您在测试类,应用程序或任何保存数据的外部位置保持状态。

例如,如果您的应用程序在一次测试中将用户保存到数据库并在另一次测试中测试该用户的存在,那么当然会使您的测试相互干扰。

所以我想你需要找出一些清理数据库的方法,你可以在每次测试之间保存数据。

相关问题