custom constructor and phpspec

103 views Asked by At

I have this class I want to test in phpspec:

class Something
{
  protected $property;

  public function __construct($someId)
  {
    $this->property = Model::find($someId);
  }
}

Model::find() returns a Model instance.

And I don't want phpspec to use the db etc. I tried

class SomethingSpec
{
  public function let(Model $model)
  {
    $this->property = $model;
  }

  it_is_initializable...

But that doesn't work.

Anybody?

1

There are 1 answers

1
Jakub Zalas On BEST ANSWER

PhpSpec encourages you to take a good care of how code is designed. Many things are not possible to prevent you from hurting yourself. This is by design. If you want to do things like you presented in the question, use another tool (phpunit for example).

Accessing Model::find($someId) from a constructor is not a good design and it's not testable (see the Dependency Inversion and other SOLID principles).

You should inject your dependency from the outside context. Either inject a Model instance or a result of Model::find() call:

class Something
{
    private $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }
}

Start with a spec first, before you write the code. It will make your life easier.