测试未登录用户回复跳转到登录界面,测试结果为 404?

test 文件:

 public function unauthenticated_user_may_no_add_replies()
    {
        $this->withExceptionHandling()->post('/threads/1/replies', [])
            ->assertRedirect('/login');
    }

web 路由文件:

Route::post('/threads/{thread}/replies','RepliesController@store')->name('reply.store');

Controller :

 public function _construct()
 {
     $this->middleware('auth');
 }
 public function store(Thread $thread)
{
  $thread->addReply([
  'body' => request('body'),
  'user_id' => auth()->id(),
  ]);

  return redirect(route('threads.show',[$thread->channel,$thread->id]));

}

测试结果:

测试未登录用户回复跳转到登录界面,测试结果为404?

找了半天不知道为什么是404 呢?

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

这里之所以是404 的问题,是因为还没有创建 thread,所以并未存在 id 为1的模型实例,所以路由

$this->post('/threads/1/replies', [])->assertRedirect('/login');

是不存在的, 所以我们需要先创建thread 实例

$thread = factory('App\Models\Thread')->create();
$this->withExceptionHandling()->post('/threads/'.$thread->id.'/replies', [])->assertRedirect('/login');
4年前 评论
讨论数量: 3
洛未必达

1.测试代码改成以下,可以看到详细错误信息:

public function unauthenticated_user_may_no_add_replies()
    {
        $this->post('/threads/1/replies', [])
            ->assertRedirect('/login');
    }

2.你定义的路由:

Route::post('/threads/{thread}/replies','RepliesController@store')->name('reply.store');

Laravel 的 路由模型绑定会先尝试查找 id 为 1 的 Thread 模型实例,然后发现找不到,于是生成 404 异常。

3.文章里面定义的路由最终形式为:

Route::post('/threads/{channel}/{thread}/replies','RepliesController@store');

检查你的路由与控制器代码,与文章是有出入的。

4年前 评论

1、测试代码我改成了:

/** @test */
    public function unauthenticated_user_may_no_add_replies()
    {
        $this->post('/threads/1/replies', [])
            ->assertRedirect('/login');
    }

测试结果:

file 页面中测试没有问题 file 2、id 为1 的thread 模型是存在的,

file

3、因为话题的回复,是用不到 channel 模型的,所以我觉得路由中无需带有channel 资源,所以这里我使用的路由是

Route::post('/threads/{thread}/replies','RepliesController@store')->name('reply.store');

同样我改为

Route::post('/threads/{channel}/{thread}/replies','RepliesController@store')->name('reply.store');

测试文件改为

/** @test */
    public function unauthenticated_user_may_no_add_replies()
    {
        $this->post('/threads/some-channel/1/replies', [])
            ->assertRedirect('/login');
    }

测试还是404,

file

4年前 评论

这里之所以是404 的问题,是因为还没有创建 thread,所以并未存在 id 为1的模型实例,所以路由

$this->post('/threads/1/replies', [])->assertRedirect('/login');

是不存在的, 所以我们需要先创建thread 实例

$thread = factory('App\Models\Thread')->create();
$this->withExceptionHandling()->post('/threads/'.$thread->id.'/replies', [])->assertRedirect('/login');
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!