我有一个包含许多示例的PHPSpec类。我希望能够在spec类中创建类变量,该类中的任何示例函数都可以使用这些变量。
以下是一个非常简化的版本:
class ThingImTestingSpec extends ObjectBehavior
{
private $common_variables_array = [
'property_1' => value_1,
'property_2' => 'Value 2'
];
function it_finds_a_common_property()
{
$object_1 = new ConstructedObject;
$this->find_the_common_property($object_1)->shouldReturn($this->common_variables_array['property_1']);
}
}问题在于PHPSpec (聪明地)如何实例化和引用被测试的类。规范方法中对$this的引用实际上指的是测试对象,而不是spec类本身。
但这意味着尝试使用$this->class_variable引用测试对象上的类变量来引用类变量,而不是使用规范。
所以。如何在spec类本身的范围内创建一组变量,这些示例可以在运行时访问这些变量?
我尝试过的事情:
beConstructedWith -需要修改测试中的类,这样就可以进行测试。不是一个干净的解决方案。我还没试过的事情:
注意:我并不是在寻找以上述方式进行测试的“替代方案”,除非它们仍然适合更广泛的需求。这个例子被大大缩减了。实际上,我正在扩展LaravelObjectBehavior (https://github.com/BenConstable/phpspec-laravel),使用规范的构造函数通过工厂和Faker类(https://github.com/thephpleague/factory-muffin)在测试数据库中创建记录,并在测试之后销毁它们(League\FactoryMuffin\Facade::deleteSaved(),在spec的析构函数中)。我希望能够在任意数量的规范函数中引用由模型(并由FactoryMuffin创建)表示的对象,因此我不必在每个规范函数中重新创建这些对象和集合。是的,我知道这超出了“规范”测试的范围,但是当一个应用程序被绑定到一个模型中时,与数据层交互的对象仍然是“spec线缆”,这是可以争辩的。
我目前正在使用phpspec 2.2.1和Laravel 4.2
发布于 2018-05-20 14:18:51
我们目前在软件中使用PHPSpec v3。请使用let方法声明常见的事物。简单的例子:
<?php
class ExampleSpec extends \PhpSpec\ObjectBehavior
{
private $example; // private property in the spec itself
function let()
{
$this->example = (object) ['test1' => 'test1']; // setting property of the spec
parent::let();
}
function it_works()
{
var_dump($this->example); // will dump: object(stdClass)#1 (1) { ["test1"] => string(5) "test1" }
}
function it_works_here_as_well()
{
var_dump($this->example); // will dump same thing as above: object(stdClass)#1 (1) { ["test1"] => string(5) "test1" }
$this->example = (object) ['test2' => 'test2']; // but setting here will be visible only for this example
}
function it_is_an_another_example()
{
var_dump($this->example); // will dump same thing first two examples: object(stdClass)#1 (1) { ["test1"] => string(5) "test1" }
}
}发布于 2017-09-24 21:26:01
找到答案了。显式声明类变量为static,规范类中的方法可以访问它们:
class ThingImTestingSpec extends ObjectBehavior
{
private static $common_variables_array = [
'property_1' => value_1,
'property_2' => 'Value 2'
];
function it_finds_a_common_property()
{
$object_1 = new ConstructedObject;
$this->find_the_common_property($object_1)->shouldReturn($this::$common_variables_array['property_1']);
}
}这适用于数组以及表示使用雄辩的方法构建的数据库记录的对象。
class LaravelAppClassImTestingSpec extends LaravelObjectBehavior
{
private static $Order_1;
function __construct()
{
$Order_1 = \Order::find(123);
}
function it_tests_a_thing()
{
//(the method has access to the static class variable via
//$this::$Order_1
}
}https://stackoverflow.com/questions/46287513
复制相似问题