【发布时间】:2013-11-02 15:18:10
【问题描述】:
我的控制器中有一个我想直接调用的方法。它接受一个 POSTed 表单,对其进行验证,然后返回一些东西。我想直接测试这个 - 即不通过路线助手。
这是我的表单代码(FormFields 只是一个案例类)
val searchForm = Form(
mapping(
"foo" -> nonEmptyText,
"filter" -> optional(text).verifying("Filter text must be 'published' or 'unpublished'",
x => x.isEmpty || x.get == "published" || x.get == "unpublished")
)(FormFields.apply)(FormFields.unapply)
)
这是我的控制器调用。
def doThings() = IsAuthenticated {
username => implicit request => {
searchForm.bindFromRequest().fold(
formWithErrors => BadRequest(s"Incorrect data: ${formWithErrors.errors.map(x => s"${x.key} ${x.message}").mkString}."),
form => {
OK("Test text here")
}
)
}
}
如果我通过我的路由文件调用它,如下所示 - 这可以按预期工作。表单已按预期发布、验证并返回 OK("Test...")。
即。以下工作(使用 Specs2)
val request = FakeRequest(POST, "notarealurl")
.withFormUrlEncodedBody(
"filter" -> "published",
"foo" -> "Test"
).withSession("email" -> "testuser")
val Some(result) = route(request)
status(result) must equalTo(OK)
但是,无论我尝试直接调用该方法都会失败 - 失败发生在表单验证步骤上。当我运行单元测试时,它告诉我“foo”缺少一个值。这就是我尝试这样做的方式。
val request = FakeRequest()
.withFormUrlEncodedBody(
"filter" -> "published",
"foo" -> "Test"
).withSession("email" -> "testuser")
//val Some(result) = route(request)
val result = Search.searchProducts()(request)
println(contentAsString(result))
status(result) must equalTo(OK)
打印的文本是“不正确的搜索:foo error.required”。我认为我没有正确拨打电话,但我不知道我哪里出错了。
注意:这里的代码代表我的问题,但已被删减以说明问题。
【问题讨论】:
-
我知道你已经说过你不想使用路线助手。但是,如果你真的使用它,它会起作用吗?
-
@LimbSoup 是的,它适用于路线助手。
标签: scala post playframework playframework-2.0 specs2