RossTsachev
RossTsachev

Reputation: 921

testing with phpspec - mocking method from the current class

I'm learning phpspec and can't figure out why a test is not passing.

Here is my function:

public function isTaskForChange($task)
{
    $supportedTasks = array_keys($this->availableTasks()); 
    $isTaskForChange = in_array($task, $supportedTasks);

    return $isTaskForChange;
}

And here is the test in phpspec:

public function it_validates_if_task_should_be_changed()
{
    $this->isTaskForChange('write')->shouldReturn(true);
}

However, when I run this code I get back:

warning: array_keys() expects parameter 1 to be array, null given

My question is: How to mock $this->availableTasks() to return values?

Upvotes: 0

Views: 1342

Answers (1)

Jakub Zalas
Jakub Zalas

Reputation: 36191

What you're trying to do is called partial mocking.

Partial mocking is not possible in phpspec on purpose. To be precise it's not possible in prophecy, the mocking framework it uses.

The reason for this is that a need for partial mocking most likely communicates a design issue (single responsibility principle violation in this case). Phpspec and prophecy are highly opinionated tools. They're designed for people who want to get their design right. Therefore some things are just not possible.

You can either fix your design, or use another mocking framework to accomplish what you need (like mockery).

You shouldn't mock the method availableTasks(), but set up your objects in a way it returns what you expect. Mock or stub the collaborators.

P.S. It's worth to read My top ten favourite PhpSpec limitations

Upvotes: 7

Related Questions