Question

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?

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top