对象构造 在phpspec规范中,您描述的对象不是一个单独的变量,而是$ this。因此,与其像这样写:
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
class MarkdownSpec extends ObjectBehavior
{
function it_converts_plain_text_to_html_paragraphs()
{
$markdown = new Markdown();
$markdown->toHtml("Hi, there")->shouldReturn("<p>Hi, there</p>");
}
}
就像使用其他工具一样,您可以这样写:
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
class MarkdownSpec extends ObjectBehavior
{
function it_converts_plain_text_to_html_paragraphs()
{
$this->toHtml("Hi, there")->shouldReturn("<p>Hi, there</p>");
}
}
因此,这意味着您不会构造示例中要描述的对象。相反,当运行规范时,phpspec会处理正在描述的对象的创建。
phpspec执行此操作的默认方式与相同。如果不需要将任何值或依赖项传递给它,则可以,但是对于许多对象而言,这将不够好。您可以告诉phpspec 您希望它如何创建对象。new Markdown()
使用构造函数 您可以告诉phpspec在构造对象时将值传递给构造器:
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
use Markdown\Writer;
class MarkdownSpec extends ObjectBehavior
{
function it_outputs_converted_text(Writer $writer)
{
$this->beConstructedWith($writer);
$writer->writeText("<p>Hi, there</p>")->shouldBeCalled();
$this->outputHtml("Hi, there");
}
}
使用工厂方法 您可能不希望使用构造函数,而是使用静态工厂方法创建类。这使您可以针对不同的用例以不同的方式创建它,因为在PHP中只能有一个构造函数。
<?php
use Markdown\Writer;
class Markdown
{
public static function createForWriting(Writer $writer)
{
$markdown = new Self();
$markdown->writer = $writer;
return $markdown;
}
}
您可以告诉phpspec这是您要如何构造对象,如下所示:
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
use Markdown\Writer;
class MarkdownSpec extends ObjectBehavior
{
function it_outputs_converted_text(Writer $writer)
{
$this->beConstructedThrough('createForWriting', [$writer]);
$writer->writeText("<p>Hi, there</p>")->shouldBeCalled();
$this->outputHtml("Hi, there");
}
}
其中第一个参数是方法名称,第二个参数是要传递给该方法的值的数组。
为了更具描述性,可以使用较短的语法。以下所有都是等效的:
$this->beConstructedNamed('Bob');
$this->beConstructedThroughNamed('Bob');
$this->beConstructedThrough('Named', array('Bob'));
覆写 为了避免重复,您可以告诉phpspec如何在let中构造对象。但是,您可能只有一个示例,需要以其他方式进行构造。您可以通过beConstructedWith在示例中再次调用来执行此操作。上一次调用beConstructedWith将确定phpspec如何构造对象:
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
use Markdown\Writer;
class MarkdownSpec extends ObjectBehavior
{
function let(Writer $writer)
{
$this->beConstructedWith($writer, true);
}
function it_outputs_converted_text(Writer $writer)
{
// constructed with second argument set to true
// ...
}
function it_does_something_if_argument_is_false(Writer $writer)
{
$this->beConstructedWith($writer, false);
// constructed with second argument set to false
// ...
}
}