Witajcie,
Mam kod w Laravelu 6. Chciałbym napisać do tego Testy.
Mój kod wygląda następująco:
- Kontroler:
public function destroy(Request $request)
{
if ($request->isMethod('post')) {
foreach ($request->input('id') as $value) {
$this->model->delete($value);
}
return redirect()->route('ads.index')->with('success', 'Rekordy zostały usunięte!');
}
}
- Model:
class Ad extends Model
{
use ScopeActiveTrait;
protected $quarded = ['id'];
protected $fillable = ['company_id', 'user_id', 'title', 'content', 'provincial_id', 'enable', 'url_address'];
public $timestamps = true;
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
}
- Test:
public function testDeleteAd()
{
$this->withExceptionHandling();
//$this->withoutExceptionHandling();
$user = User::find(1);
$this->be($user);
$ad = factory(Ad::class)->create();
//$this->post(route('ads.destroy'), ['id[]' => $ads->toArray(), '_token' => csrf_token()]);
//$response = $this->call('POST', route('ads.destroy'), ['_token' => csrf_token(), 'id[]' => $ads->toArray(), 'id' => $ads->toArray()]); dd($response);
//$this->assertDatabaseMissing('ads', ['id' => $ads->id]);
$ad = Ad::where('id', $ad->id)->first();
$response = $this->post(route('ads.destroy'), [
'id' => $ad->id,
'_token' => csrf_token()
]);
$this->assertDatabaseMissing('ads', ['id' => $ad->id]);
}
Kiedy uruchamiam test otrzymuję błąd:
root@142d1f3c30d0:/var/www# vendor/bin/phpunit --filter AdTest
PHPUnit 9.0.1 by Sebastian Bergmann and contributors.
F 1
/ 1 (100%)
Time: 1.83 seconds, Memory: 26.00 MB
There was 1 failure:
1) Tests\Feature\AdTest::testDeleteAd Failed asserting that a row in
the table [ads] does not match the attributes {
"id": 9 }.
Found similar results: [
{
"id": 9,
"company_id": 1,
"user_id": 1,
"title": "Dolore similique magnam tempora esse a ex ut excepturi.",
"content": "Itaque animi fugit quod unde. Accusamus recusandae sit non quia cupiditate aspernatur. Sunt quas accusamus recusandae
eius doloribus sequi.",
"provincial_id": 2,
"enable": "0",
"url_address": "dolore-similique-magnam-tempora-esse-a-ex-ut-excepturi",
"created_at": "2020-04-27 05:59:57",
"updated_at": null
} ].
/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php:45
/var/www/tests/Feature/AdTest.php:71
W jaki sposób mogę to naprawić? Dlaczego wyskakuje tutaj błąd?
Rekord w bazie jest poprawnie utworzony, nie kasuje się i wyskakuje powyższy błąd