Last active
May 14, 2019 21:30
-
-
Save rafaelgfirmino/8e4575ff5b2bea0238eb3ee3e76edc03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests; | |
use Illuminate\Foundation\Http\FormRequest; | |
use Illuminate\Support\Collection; | |
use Illuminate\Support\Facades\Validator; | |
trait AssertRequestRules | |
{ | |
protected function assertRequestRuleHasError($field, $value, FormRequest $request, array $attributes = []) | |
{ | |
$result = $this->checkRequestRule($field, $value, $request, $attributes)->offsetExists($field); | |
if ($result) { | |
self::assertTrue($result, "Session missing error: $result"); | |
} else { | |
$error = "This field '{$field}' don't contains error. \n"; | |
self::assertContains('true', $result ? 'true' : 'false', $error); | |
} | |
} | |
protected function assertRequestRuleNoHasError($field, $value, FormRequest $request, array $attributes = []) | |
{ | |
$collection = $this->checkRequestRule($field, $value, $request, $attributes); | |
$result = $collection->offsetExists($field); | |
if (!$result) { | |
self::assertFalse($result, "Session missing error: $result"); | |
} else { | |
$error = $this->getErrorMessage($field, $collection); | |
self::assertContains('false', $result ? 'true' : 'false', $error); | |
} | |
} | |
private function checkRequestRule($field, $value, FormRequest $request, array $attributes = []):Collection | |
{ | |
$rules = $request->rules(); | |
$attributes = array_merge($attributes, [$field => $value]); | |
$validator = Validator::make($attributes, $rules); | |
$fails = $validator->errors(); | |
$collection = collect($fails); | |
return $collection; | |
} | |
private function getErrorMessage($field, Collection $collection) | |
{ | |
$error = "Errors in '${field}' field : \n"; | |
foreach ($collection[$field] as $ruleError) { | |
$error .= " - {$ruleError} \n"; | |
} | |
return $error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment