mohammedmanssour / form-request-tester
一组测试辅助函数,帮助测试表单请求
1.2.2
2024-01-05 07:56 UTC
Requires (Dev)
- orchestra/testbench: ~6.0
This package is auto-updated.
Last update: 2024-09-05 09:18:44 UTC
README
这是一个简单的测试辅助函数集合,可以轻松测试表单请求。
为什么这样做
有关为什么构建此包的完整故事,请参阅这篇博客文章
安装
- 使用 composer
composer require --dev mohammedmanssour/form-request-tester
- 将
MohammedManssour\FormRequestTester\TestsFormRequests
特性添加到您的测试用例中。
测试表单请求
- 您需要使用
formRequest
方法初始化表单请求,它以表单请求类作为第一个参数,以及一个请求数据数组作为第二个参数
$this->formRequest(UpdatePost::class, [ 'title' => 'New Title', 'content' => 'Some Content here' ])
或者,您可以使用直观的方法来设置表单请求方法和数据
$this->formRequest(UpdatePost::class) ->post([ 'title' => 'New Title', 'content' => 'Some Content here' ])
前面的代码将使用 post
方法初始化请求到 /fake-route
,如果您想更改这些选项,可以通过选项数组来设置第三个参数
$this->formRequest(UpdatePost::class, [ 'title' => 'New Title', 'content' => 'Some Content here' ], [ 'method' => 'put', 'route' => 'posts/{post}' ])
$this->formRequest(UpdatePost::class) ->put([ 'title' => 'New Title', 'content' => 'Some Content here' ]) ->withRoute('posts/{post}')
- 使用可用的断言来测试请求
可用断言
示例用法
考虑到
- 标题和内容是必填字段,
- 内容字段是必填的 是用于内容字段的自定义错误消息
$this->route
方法在授权方法中使用Route::put('posts/{post}', 'PostsController@update')
是更新帖子所使用的路由
$this->formRequest(UpdatePost::class,[ 'title' => 'New Title' ],[ 'method' => 'put' 'route' => 'posts/{post}' ])->assertAuthorized() ->assertValidationFailed() ->assertValidationErrors(['content']) ->assertValidationErrorsMissing(['title']) ->assertValidationMessages(['Content field is required'])
您现在可以使用直观的方法来构建表单请求
$this->formRequest(UpdatePost::class) ->put([ 'title' => 'New Title' ]) ->withRoute('posts/1') ->assertAuthorized() ->assertValidationFailed() ->assertValidationErrors(['content']) ->assertValidationErrorsMissing(['title']) ->assertValidationMessages(['Content field is required'])
与表单请求相关的方法及其使用方法
$this->route('parameter')
:
此方法基本上检索路由规则参数的值。
例如,如果您有一个路由规则 put posts/{post}
并且浏览到 posts/1
,则 $this->route('post')
的值是 1。为了使用此包实现这一点,您需要
- 在您的应用程序路由文件
web.php
或api.php
中注册路由规则
Route::put('posts/{post}', [PostsController::class, 'update']);
- 使用 FormRequestTester 的
withRoute
方法设置路由
$this->formRequest(UpdatePost::class) ->put($data) ->withRoute('posts/1');
这就是为什么当您在表单请求中使用 $this->route('post')
时,结果将是 1。
此包还支持绑定替换。您只需创建一个显式绑定,它就会为您完成工作。
// somewhere in your app 🤔, ideally, your service provider Route::model('post', Post::class);
在注册时,$this->route('post')
的值将是一个 Post 模型,而不是 ID。
或者
如果您不想仅为了解决路由参数而注册路由,则可以使用 FormRequestTester 的 addRouteParameter($name, $value)
。
$this->formRequest(UpdatePost::class) ->put($data) ->addRouteParameter('post', 1) ->assertAuthorized();
根据上面的示例,使用新的 addRouteParameter
方法,$this->route('post')
将解析为 1
$this->user()
:
此方法将检索当前认证用户。
使用 laravel 测试方法 actingAs
来设置当前认证用户
$user = User::factory()->create(); $this->actingAs($user);