1

假设我有 RuleFactory 的这种方法:

public function makeFromArray($rules)
{
    $array = [];
    foreach ($rules as $rule) {
        $array[] = new Rule($rule[0], $rule[1]);
    }

    return $array;
}

我想测试返回数组是否包含 Rule 元素。这是我的测试:

function it_should_create_multiple_rules_at_once()
{
    $rules = [
        ['required', 'Please provide your first name'],
        ['alpha', 'Please provide a valid first name']
    ];

    $this->makeFromArray($rules)->shouldHaveCount(2);
    $this->makeFromArray($rules)[0]->shouldBeInstanceOf('Rule');
    $this->makeFromArray($rules)[1]->shouldBeInstanceOf('Rule');
}

但这不起作用,它会在 PHPSpec 中引发错误。

奇怪的是,我可以在其他返回数组的方法上很好地做到这一点,但由于某种原因,我不能在这里做到这一点。

我得到的错误是这样的:

! it should create multiple rules at once
      method [array:2] not found

如何在不创建自己的内联匹配器的情况下测试此返回数组的内容?

4

1 回答 1

2

您的方法接受一个规则,而不是所有规则。规范应该是:

$this->makeFromArray($rules)->shouldHaveCount(2);
$this->makeFromArray($rules[0])[0]->shouldBeAnInstanceOf('Rule');
$this->makeFromArray($rules[1])[1]->shouldBeAnInstanceOf('Rule');

或者,为了避免多次调用:

$rules = $this->makeFromArray($rules);
$rules->shouldHaveCount(2);
$rules[0]->shouldBeAnInstanceOf('Rule');
$rules[1]->shouldBeAnInstanceOf('Rule');

尽管如此,最易读的版本将是利用自定义匹配器的版本:

$rules->shouldHaveCount(2);
$rules->shouldContainOnlyInstancesOf('Rule');
于 2014-09-08T19:45:30.083 回答