gpt4 book ai didi

php - Laravel 5.1 测试环境中的 Eloquent 模型事件

转载 作者:行者123 更新时间:2023-12-04 18:03:20 24 4
gpt4 key购买 nike

我有一个 Eloquent我在模型的 boot() 中定义了一些观察者方法的模型方法。这是一个非常简单的逻辑 - 我使用 creating()如果在调用 Model::create([...]) 时尚未定义属性,则为属性定义默认值的静态方法.

protected static function boot()
{
parent::boot();
static::creating(function (Content $content) {
static::setDefaultValues($content);
});
}

protected static function setDefaultValues(Content $content)
{
if ( ! $content->published_at) {
$content->published_at = Carbon::now();
}
}

通过浏览器或控制台使用应用程序时一切正常 artisan tinker ,或数据库播种机。

但是,当我在测试用例运行时尝试使用相同的数据库种子设定逻辑通过 artisan 命令引导测试数据库时,我收到异常抛出说特定属性不能为 NULL。我对 Laravel 代码做了一些研究和挖掘,发现事件调度程序应该正常运行,因为我没有模拟任何事件,也没有使用 withoutEvents()。 helper 。

此外,全局范围似乎没有在测试环境中正确应用。

我已将 var_dumps 放置在几个关键点上(在调用 creating() 之后,在 Eloquent\Model 方法中的 save() 类中,以及在触发模型事件之后)检查属性并注意到观察者方法 正在被执行,但效果就好像模型实例不是通过引用传递给事件处理程序,而是被克隆。相同的代码在开发环境中运行正常,但在测试环境中失败。

有人遇到过这种情况吗?我不太确定如何进行,因此非常欢迎任何建议。

就其值(value)而言,我在开发中使用 MySQL 并尝试在 SQLite 数据库中运行测试以便于使用。这些测试正在使用 Laravel 开箱即用的 PHPUnit 测试设置运行。

最佳答案

将所有模型事件绑定(bind)的声明移动到 AppServiceProvider::boot() 方法,如下所示

class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
\App\Content::creating(function (Content $content) {
$content::setDefaultValues($content); // change to public
});

// other bindings
}

/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

关注http://laravel.com/docs/5.1/eloquent#events

您也可以使用该方法来附加模型观察者。

关于php - Laravel 5.1 测试环境中的 Eloquent 模型事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31542446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com