说我有这个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
如何在不创建自己的内联匹配器的情况下测试此返回数组的内容?
答案 0 :(得分: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');