【发布时间】:2016-10-02 06:55:24
【问题描述】:
我从控制器的方法返回一个视图,如下所示:
return view('Main::pages.content-page', compact('content'));
视图正确呈现,但是,当我 dd 响应对象时,我看到响应对象的属性“原始”是一个字符串,而它应该是视图对象。
Response {#385 ▼
+original: """
<!DOCTYPE html>\n
<html lang="en">\n
<head>\n
<meta charset="utf-8">\n
<meta http-equiv="X-UA-Compatible" content="IE=edge">\n
<meta name="viewport" content="width=device-width, initial-scale=1">\n
<meta name="author" content="">\n
<meta name="csrf-token" content="2CQirHnZ7isCBRfkhOYkzPAWOzNIqJISrbb1mfDv">\n
<meta name="description" content="">\n
<meta name="keywords" content="">\n
<title id="page_title"> Découvrir\n </title>\n
.........
这是预期的行为,因为我的测试实际上因此而失败,因为在我的测试中基本上是在做
$this->get(route('main.page', ['content' => $content->slug]))
->assertResponseOk()
->assertViewHas('content', $content);
我遇到了以下故障
F 1 / 1 (100%)
Time: 179 ms, Memory: 20.00MB
There was 1 failure:
1) IndexControllerTest::testGetPageMethod
The response was not a view.
Failed asserting that false is true.
查看assertViewHas()方法的结构我们就知道为什么了
/**
* Assert that the response view has a given piece of bound data.
*
* @param string|array $key
* @param mixed $value
* @return $this
*/
public function assertViewHas($key, $value = null)
{
if (is_array($key)) {
return $this->assertViewHasAll($key);
}
if (! isset($this->response->original) || ! $this->response->original instanceof View) {
return PHPUnit::assertTrue(false, 'The response was not a view.');
}
......
条件 ! $this->response->original instanceof View 失败,因为 original 是一个字符串,但应该是一个视图对象。
所以我在这里迷路了。如果是这样,这是预期的行为,为什么 assertViewHas 方法中的条件?
I am on Laravel Homestead version '3.0.2'
Laravel 5.2.45
【问题讨论】:
-
View implements
__toString()。我不知道这是否是原因,但值得检查 Laravel 是否在调用 this 的字符串上下文中使用 View。 -
实现 __toString() 作为将视图转换为字符串的方式。它的默认视图对象。您应该检查您的视图是否正确模板化为刀片模板
-
是视图实现 __toString() 但响应对象应该只将视图转换为字符串并将其设置为它的“内容”属性,响应对象的属性“原始”应该始终是原始视图对象。
标签: php unit-testing laravel-5.2 httpresponse