Last active
January 17, 2019 14:50
-
-
Save mattias-persson/f6f387896a9dfc0d1537f4210ff21fe4 to your computer and use it in GitHub Desktop.
Laravel PHPUnit - Nice helpers
This file contains 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
/** | |
* Assert that a model contains an exact set of attributes. | |
* Example: $this->assertModelHasExactAttributes($user, ['email', 'password', 'created_at']); | |
* | |
* @param Illuminate\Database\Eloquent\Model $model | |
* @param array $attributes | |
* @return Illuminate\Foundation\Testing\TestCase | |
*/ | |
public function assertModelHasExactAttributes($model, $attributes = []) | |
{ | |
$model = $model->toArray(); | |
$count = count($model); | |
foreach ($attributes as $attribute) { | |
$this->assertArrayHasKey($attribute, $model); | |
$count--; | |
} | |
if ($count > 0) { | |
$this->fail('The model has more attributes than expected.'); | |
} | |
return $this; | |
} | |
/** | |
* Assert that a model contains a set of attributes. | |
* Example: $this->assertModelHasAttributes($user, ['email']); | |
* | |
* @param Illuminate\Database\Eloquent\Model $model | |
* @param array $attributes | |
* @return Illuminate\Foundation\Testing\TestCase | |
*/ | |
public function assertModelHasAttributes($model, $attributes = []) | |
{ | |
$model = (array)$model; | |
foreach ($attributes as $attribute) { | |
$this->assertArrayHasKey($attribute, $model); | |
} | |
return $this; | |
} | |
/** | |
* Assert a dataset has all expected keys. | |
* | |
* @param mixed $data | |
* @param array $expectedKeys | |
* @return void | |
*/ | |
public function assertHasKeys($data, $expectedKeys) | |
{ | |
if (!is_array($data)) { | |
$data = (array) $data; | |
} | |
$keys = array_keys($data); | |
$missingKeys = []; | |
foreach ($expectedKeys as $key) { | |
if (in_array($key, $keys)) { | |
$this->assertTrue(true); | |
} else { | |
$missingKeys[] = $key; | |
} | |
} | |
if (!empty($missingKeys)) { | |
$this->fail('The dataset is missing the following keys: '.implode(', ', $missingKeys)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment