Search code examples
phpphpspec

Stub for formal parameter passed by reference in PHPSpec/Prophecy


I have a method in PHP which looks like this:

<?php
class SomeClass
{
    public function isEntitledToDiscount(GuestModel $who, $onWhat, &$discountAmount = null)
    {
        $discountAmount = 10;
        return true;
    }
}

Is there a way to stub $discountAmount in PHPSpec? Let's say I have a class I'm testing, and I've injected $someService via constructor. In my spec I use:

<?php
$someService->isEntitledToDiscount($guest, $ticket, $discountAmount)->willReturn(true);

which creates stub for method return value. How can I do this with the $discountAmount formal parameter?


Solution

  • A method shouldn't modify its arguments (shouldn't have side effects). Especially a getter-type method. You should probably rethink your design.

    Your problem is actually related to prohpecy, so you might want to read its docs: https://github.com/phpspec/prophecy

    Prophecy (and PhpSpac) make some things hard. In most cases it means that you're trying to take a wrong turn with your design.

    You could try the following, but I don't think you'll get a reference to your variable:

    $someService->isEntitledToDiscount($guest, $ticket, $discountAmount)
        ->will(function ($arguments) {
            // do your evil
        });
    

    Recommended read: Command Query Separation.