我只是想测试一个简单的输入字段,但我得到了这个错误!
/** @test */
public function email_must_be_a_valid_email()
{
$response = $this->post('/api/contacts', array_merge($this->data(), ['email' => 'NOT AN EMAIL']));
$response->assertSessionHasErrors('email');
}
private function data()
{
return [
'name' => 'Test Name',
'email' => 'test@hotmail.com',
'birthday' => '05/14/1988',
'company' => 'ABC String'
];
}
它们是控制器和请求规则。我希望你能帮助我。
class StoreController extends Controller
{
public function store(ContactsRequest $request)
{
$data = $request->validated();
Contact::create($data);
}
}
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'birthday' => 'required',
'company' => 'required',
];
}
我希望你能帮我。
如果您正在使用api路由,那么您应该使用
$response->assertJsonValidationErrors(['email']);
或
$response->assertInvalid(['email']);
它适用于JSON和会话错误。
https://laravel.com/docs/8.x/http-tests#assert-invalid
谢谢你的提示。我已经解决了这个问题!但这种错误消息根本无助于快速找到解决方案。解决方案是,我需要登录以创建联系人,然后验证表单数据。但是错误消息说明了完全不同的事情!
protected $user;
protected function setUp(): void
{
parent::setUp();
$this->user = User::factory()->create();
$this->user->createToken(Str::random(30))->plainTextToken;
}
/** @test */
public function email_must_be_a_valid_email()
{
$this->actingAs($this->user);
$response = $this->post('/api/contacts', array_merge($this->data(), ['email' => 'NOT AN EMAIL']));
$response->assertSessionHasErrors('email');
}