首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TDD Laravel - laravel特征测试和空间/laravel-activitylog获取JSON编码错误

TDD Laravel - laravel特征测试和空间/laravel-activitylog获取JSON编码错误
EN

Stack Overflow用户
提问于 2017-12-13 17:38:48
回答 2查看 1.6K关注 0票数 4

我正在用laravel为我的模型编写一些测试,当我使用空间/拉拉-活动日志启用活动日志时,我遇到了一些麻烦。

因此,我创建了一个用户,使用Factory在系统中进行身份验证,当我尝试注销时,我得到了以下错误:

Tests\Feature\Usuario\CriarUsuarioTest::testAcessaPaginaDeRegistro Illuminate\Database\Eloquent\JsonEncodingException:无法为模型Spatie\Activitylog\\Activitylog\Activitylog\Activity编码JSON的属性属性:::不支持.

我的测试TestCase.php

代码语言:javascript
复制
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模型:

代码语言:javascript
复制
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文件:

代码语言:javascript
复制
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文件:

代码语言:javascript
复制
<?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文件:

代码语言:javascript
复制
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');
    }
}

我注意到,当我禁用活动日志的模型,它的工作很好。而且,当我通过修补程序或浏览器使用系统时,日志也可以工作。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-03 13:55:42

我无法重现错误,但我确实有一些注意事项:

  • 您说当您发布到注销路由时会触发错误,但这不应该触发活动记录器,对吗?我的意思是,在那里不会触发createdupdateddeleted事件。
  • 相反,当您使用工厂创建用户时,确实会触发一个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\HasAttributes@castAttributeAsJson方法中抛出的,该方法对属性值执行一个简单的json_encode
  • encode(),如资源。
  • 正在编码的值。可以是除资源以外的任何类型。
  • 那么,资源是否有可能被记录为properties的一部分?在创建用户之后尝试dd($user->attributeValuesToBeLogged('created'))
票数 1
EN

Stack Overflow用户

发布于 2018-01-03 14:21:14

我找到了答案(但我不知道这是否是最好的解决办法);

只要将一个$this->createApplication();放在SetUp方法中,在TestCase.php文件中,错误就会消失。

谢谢大家伙计们。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47799161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档