Task 6 - duplicate values

This commit is contained in:
PovilasKorop
2021-11-09 10:44:29 +02:00
parent 16a72f52c2
commit 888d5d87c2
4 changed files with 68 additions and 0 deletions
+8
View File
@@ -79,3 +79,11 @@ Test method `test_repeating_column_table()`.
---
## Task 6. Duplicate Column Value
Folder `database/migrations/task6` contains a migration for companies table. Edit that migration, so that it would be impossible to create multiple companies with the same name.
Test method `test_duplicate_name()`.
---
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
use HasFactory;
protected $fillable = ['name'];
}
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCompaniesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// TASK: edit this migration so there couldn't be two companies with the same name
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('companies');
}
}
+14
View File
@@ -3,9 +3,11 @@
namespace Tests\Feature;
use App\Models\Category;
use App\Models\Company;
use App\Models\Product;
use App\Models\Project;
use App\Models\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;
@@ -72,4 +74,16 @@ class MigrationsTest extends TestCase
Artisan::call('migrate:fresh', ['--path' => '/database/migrations/task5']);
}
public function test_duplicate_name()
{
// We expect that the second Company::create() would throw an exception like
// "Integrity constraint violation: 1062 Duplicate entry 'Company One'"
$this->expectException(QueryException::class);
Artisan::call('migrate:fresh', ['--path' => '/database/migrations/task6']);
Company::create(['name' => 'Company One']);
Company::create(['name' => 'Company One']);
}
}