据我了解,RefreshDatabase会删除测试期间创建的记录。此功能测试中的帖子不会保存记录,实际上会截断测试运行之前创建的记录。
Patient_details在模型中已加密/序列化。从前端发布,可以很好地存储一切。但是,一旦我运行测试,表就会被截断。我试过重新安装MySQL服务器,php artisan config:clear和cache:clear。我没有收到任何错误,并且Patient :: create似乎执行得很好。我还使用sqlite数据库对此进行了测试,并获得了相同的行为。
测试
<?php
namespace Tests\Feature;
use App\Patient;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\withoutExceptionHandling;
use Illuminate\Support\Facades\Crypt;
use Tests\TestCase;
class PatientTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function patient_details_are_posted_encrypted_and_saved()
{
$this->withoutExceptionHandling();
$newPatient = factory('App\Patient')->make();
$response = $this->post('/patient', $newPatient->patient_details);
$patients = new Patient;
$patients->all();
$patient = $patients->last();
$this->assertEquals($newPatient->patient_details, Crypt::decrypt($patient->patient_details));
}
}
Controller @ store
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$attributes = request()->validate([
'prefix' => 'nullable',
'first_name' => 'required',
'middle_name' => 'nullable',
'last_name' => 'required',
'suffix' => 'nullable',
'sex' => 'nullable',
'street_address' => 'required',
'city' => 'required',
'state' => 'required',
'zip' => 'required',
'home_phone' => 'nullable',
'work_phone' => 'nullable',
'cell_phone' => 'nullable',
'email' => 'required',
'dob' => 'nullable|date'
]);
Patient::create(['patient_details' => $attributes]);
return redirect('/');
}
应用\患者
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
class Patient extends Model
{
protected $guarded = [];
public static function boot()
{
parent::boot();
self::creating(function($model){
$model->patient_details = Crypt::encrypt($model->patient_details);
});
}
}
答案 0 :(得分:1)
我认为该特征 RefreshDatabase 基本运行以下方法
protected function refreshTestDatabase()
{
if (! RefreshDatabaseState::$migrated) {
$this->artisan('migrate:fresh', [
'--drop-views' => $this->shouldDropViews(),
'--drop-types' => $this->shouldDropTypes(),
]);
$this->app[Kernel::class]->setArtisan(null);
RefreshDatabaseState::$migrated = true;
}
$this->beginDatabaseTransaction();
}
并且您可以看到上面的方法正在调用migration:fresh。并且如果您运行migration:新鲜的--help,您将看到描述中写的内容
说明: 删除所有表并重新运行所有迁移
因此,基本上使用RefreshDatabase特征将删除所有表并再次迁移它们。也许您可以为此目的使用DatabaseTransactions,但我猜它不会删除迁移。