2017-12-13 3 views
4

laravel에서 내 모델에 몇 가지 테스트를하고 있는데 spatie/laravel-activitylog을 사용하여 활동 로그를 활성화 할 때 몇 가지 문제가 있습니다.TDD Laravel - laravel 및 spatie/laravel-activitylog의 기능 테스트에서 JSON 인코딩 오류가 발생합니다.

그래서, 내가 Factory를 사용하여 사용자를 생성, 나는 시스템에서 인증하고, 내가 로그 아웃하려고합니다 때이 오류가 얻을 :

1) Tests\Feature\Usuario\CriarUsuarioTest::testAcessaPaginaDeRegistro Illuminate\Database\Eloquent\JsonEncodingException: Unable to encode attribute [properties] for model [Spatie\Activitylog\Models\Activity] to JSON: Type is not supported.

내 시험 TestCase.php :

protected function setUp() 
{ 
    parent::setUp(); 
    $this->user = create('App\Models\Usuario'); 
    $this->singIn($this->user) 
     ->disableExceptionHandling(); 

} 

... 
... 
... 

protected function singIn($user) 
{ 
    $this->actingAs($user); 
    return $this; 
} 

protected function singOut() 
{ 
    // routeLogout() goes to '/logout' route. 
    $this->post(routeLogout()); // <- Here, where the error occurs 
    return $this; 
} 

App/Models/Usuario.php 모델 :

namespace App\Models; 

use Illuminate\Notifications\Notifiable; 
use Illuminate\Database\Eloquent\SoftDeletes; 
use Illuminate\Foundation\Auth\User as Authenticatable; 
use Webpatser\Uuid\Uuid; 
use Spatie\Activitylog\Traits\LogsActivity; 

class Usuario extends Authenticatable 
{ 
    use LogsActivity, Notifiable, SoftDeletes; 
    protected $table = 'usuario'; 
    protected $fillable = [/*...*/] ; // I remove this to post here on SO 
    protected static $logFillable = true; 
    public $timestamps = true; 
    protected $dates = [ 
     'created_at', 
     'updated_at', 
     'deleted_at' 
    ]; 
    protected static function boot() 
    { 
     // Handle the \LogsActivity boot method 
     parent::boot(); 
     static::saving(function ($usuario){ 
      $usuario->uuid = Uuid::generate()->string; 
     }); 
    } 
    public function getRouteKeyName() 
    { 
     return 'uuid'; 
    } 
} 

config/activitylog.php FIL E :

return [ 
    'enabled' => env('ACTIVITY_LOGGER_ENABLED', true), 
    'delete_records_older_than_days' => 365, 
    'default_log_name' => 'default', 
    'default_auth_driver' => null, 
    'subject_returns_soft_deleted_models' => false, 
    'activity_model' => \Spatie\Activitylog\Models\Activity::class, 
]; 

phpunit.xml 파일 :

<?xml version="1.0" encoding="UTF-8"?> 
    <phpunit backupGlobals="false" 
      backupStaticAttributes="false" 
      bootstrap="vendor/autoload.php" 
      colors="true" 
      convertErrorsToExceptions="true" 
      convertNoticesToExceptions="true" 
      convertWarningsToExceptions="true" 
      processIsolation="false" 
      stopOnFailure="false"> 
       <testsuites> 
         <testsuite name="Feature"> 
          <directory suffix="Test.php">./tests/Feature</directory> 
         </testsuite> 
         <testsuite name="Unit"> 
          <directory suffix="Test.php">./tests/Unit</directory> 
         </testsuite> 
       </testsuites> 
       <filter> 
        <whitelist processUncoveredFilesFromWhitelist="true"> 
         <directory suffix=".php">./app</directory> 
        </whitelist> 
       </filter> 
       <php> 
        <env name="APP_ENV" value="testing"/> 
        <env name="CACHE_DRIVER" value="array"/> 
        <env name="SESSION_DRIVER" value="array"/> 
        <env name="QUEUE_DRIVER" value="sync"/> 
        <env name="API_DEBUG" value="true"/> 
        <env name="memory_limit" value="512M"/> 
        <env name="APP_DATABASE" value="test"/> 
       </php> 
    </phpunit> 

create_activity_log_migration 파일 : 나는 모델 활동 로그를 사용하지 않는 경우 그때 알

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateActivityLogTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    */ 
    public function up() 
    { 
     Schema::create('activity_log', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('log_name')->nullable(); 
      $table->string('description'); 
      $table->integer('subject_id')->nullable(); 
      $table->string('subject_type')->nullable(); 
      $table->integer('causer_id')->nullable(); 
      $table->string('causer_type')->nullable(); 
      $table->text('properties')->nullable(); 
      $table->timestamps(); 

      $table->index('log_name'); 
     }); 
    } 

    /** 
    * Reverse the migrations. 
    */ 
    public function down() 
    { 
     Schema::drop('activity_log'); 
    } 
} 

, 그 잘 작동. 그리고, 내가 땜장이 나 브라우저로 시스템을 사용할 때 로그도 잘 작동합니다.

+0

'routeLogout()'의 정의를 보여줄 수 있습니까? – Camilo

+0

죄송합니다, 깜 빡합니다. 'routeLogout()'는'/ logout' 경로를 돕는 역할을합니다. – Abe

+0

'/ logout' 경로에 대한 요청을받는 방법을 보여줄 수 있습니까? – Camilo

답변

1

내가 오류를 재현 할 수 없었다,하지만 몇 가지 고려해야합니까 : 당신은 로그 아웃 경로에 게시 할 때 오류가 트리거라고

  • 을하지만, 그 활동 실행되지 않습니다 로거, 맞지? 즉, created, updated 또는 deleted 이벤트가 발생하지 않습니다.
  • 대신 공장에서 사용자를 만들면 created 이벤트가 트리거됩니다. 그러면 활동 로그가 트리거됩니다.
  • 로거가 Activity을 새로 만들려고하면 Illuminate\Database\Eloquent\JsonEncodingException: Unable to encode attribute [properties] for model [Spatie\Activitylog\Models\Activity] to JSON: Type is not supported. 예외가 발생합니다. 이는 거의 Illuminate\Database\Eloquent\Concerns\[email protected]stAttributeAsJson 메서드에서 발생합니다.이 메서드는 특성 값에 간단한 json_encode을 사용합니다. properties의 일부
  • JSON_ERROR_UNSUPPORTED_TYPE - A value of an unsupported type was given to json_encode(), such as a resource.

  • The value being encoded. Can be any type except a resource.

  • 그래서, 어떤 기회가 자원이 기록 될 것입니다? 사용자 생성 직후 dd($user->attributeValuesToBeLogged('created'))을 시도하십시오.
0

답변을 찾았습니다 (그러나이 문제를 해결하는 가장 좋은 방법인지는 모르겠 음).

$this->createApplication();SetUp 방법에 넣는 것만으로 TestCase.php 파일에 오류가 사라집니다.

감사합니다.