karolf's avatar
Level 10

[PHPSpec] - should I need to tell a mock what it should return twice?

Hi mates, I want to start using PHPSpec so I'm start with two simple ecommerce functionality classes. The first class is intented to calculate percent of a given number called PercentNumberCalculator and the second class called PriceCalculator is responsible for applying discount for a given price which is using a PercentNumberCalculator collabolator and I need a clarification at this point. I'm include the specs of these classes below, and I have a question for a line:

$percentNumberCalculator->calculate(20, 100)->shouldBeCalled()->willReturn(20.00);

in the PriceCalculatorSpec:

<?php

namespace spec\Cve;

use Cve\PercentNumberCalculator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class PriceCalculatorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Cve\PriceCalculator');
    }

    function let(PercentNumberCalculator $percentNumberCalculator)
    {
        $this->beConstructedWith($percentNumberCalculator);
    }

    function it_returns_80_for_100_after_20_percent_discount(PercentNumberCalculator $percentNumberCalculator)
    {
        $percentNumberCalculator->calculate(20, 100)->shouldBeCalled()->willReturn(20.00);

        $this->discount(20, 100)->shouldReturn(80.00);
    }
}

Should I call the willReturn method like above? If I remove it then its example in "phpspec run" not pass, otherwise should I tell to collabolator what It should return again? (the PercentNumberCalculatorSpec has own specs for the calculate method)

PercentNumberCalculatorSpec:

<?php

namespace spec\Cve;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class PercentNumberCalculatorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Cve\PercentNumberCalculator');
    }

    function it_returns_10_for_10_percent_of_100()
    {
        $this->calculate(10, 100)->shouldReturn(10);
    }

    function it_returns_5_for_5_percent_of_100()
    {
        $this->calculate(5, 100)->shouldReturn(5);
    }
}
0 likes
0 replies

Please or to participate in this conversation.