gpt4 book ai didi

PHPSpec 和 Laravel

转载 作者:行者123 更新时间:2023-11-28 21:04:51 25 4
gpt4 key购买 nike

如果我无法访问或使用任何 Eloquent 方法,使用 PHPSpec 有什么意义?

例如:($this 指的是 Eloquent Product 模型)

function it_removes_property(PropertyValueInterface $property)
{
$this->addProperty($property);
$this->properties->shouldHaveCount(1);

$this->removeProperty($property);
$this->properties->shouldHaveCount(0);
}

这不会起作用,因为在方法 addPropertyremoveProperty 中调用了各种 Eloquent Collection 和 Model 函数,似乎 PHPSpec 无法处理,即使所有这些类包含在 use 语句中。

我注意到在 Jeffery Way 在 Laracasts 上的投屏中,他从未使用过真正的 Eloquent 模型。他只使用 vanilla PHP 对象。那有什么意义呢?那不是现实世界。

此外,这与正确引用 Eloquent 模型类无关,因为我已经这样做了 use Illuminate\Database\Eloquent\Model;

此外,我从不使用外观。所以也不是那样。

最佳答案

PHPSpec 不能做很多您可以做的事情,例如,用 PHPUnit 和 Mockery 做。
底线:我认为 PHPSpec 不是测试 Eloquent 的正确工具。

Eloquent 内部发生了很多“魔法”,而 PHPSpec 似乎并不喜欢魔法,如果你觉得你必须使用 PHPSpec 来测试 Eloquent,否则世界就会 splinter ,那么这里是您可以做几件事。

免责声明: 我不是鼓励你继续使用 PHPSpec 进行 Eloquent 测试,事实上我不希望你用它来测试 Eloquent 模型,我只是解释一些在测试魔术方法和魔法时解决您将遇到的情况的技巧 - 希望您能够在有意义的时候将它们应用到其他地方。对我来说,在 Eloquent 模型的情况下没有意义。

所以这是列表:

  • 不要使用神奇的 getter 和 setter,而是使用 getAttribute()setAttribute()
  • 不要对延迟加载的关系使用魔术调用,即 $user->profile。使用方法 $user->profile()->getResults()
  • 创建一个 SUT 模拟类来扩展您的模型并在其上定义那些 where 方法,还定义作用域方法以及 Eloquent 应该“神奇地”为您做的所有其他事情。
  • 使用 beAnInstanceOf() 方法切换到 mock 并对其进行断言。

这是我的测试的示例:

产品型号

use Illuminate\Database\Eloquent\Model;    

class Product extends Model
{
public function scopeLatest($query)
{
return $query->where('created_at', '>', new Carbon('-1 week'))
->latest();
}

// Model relations here...
}

产品型号说明

<?php namespace Spec\Model;

use Prophecy\Argument;
use App\Entities\Product;
use PhpSpec\ObjectBehavior;

class ProductSpec extends ObjectBehavior
{
public function let()
{
$this->beAnInstanceOf(DecoyProduct::class);
}

public function it_is_initializable()
{
$this->shouldHaveType('Product');
}
}

// Decoy Product to run tests on
class DecoyProduct extends Product
{
public function where();

// Assuming the Product model has a scope method
// 'scopeLatest' on it that'd translate to 'latest()'
public function latest();

// add other methods similarly
}

通过在诱饵类上定义 wherelatest 方法并使其成为 SUT,您让 PHPSpec 知道这些方法确实存在于类中。它们的参数和返回类型并不重要,重要的是存在。

优势 ?
现在在您的规范中,当您在模型上调用 ->where()->latest() 方法时,PHPSpec 不会提示它,您可以更改方法诱饵类返回一个 Prophecy 的对象并对其进行断言。

关于PHPSpec 和 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27489636/

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