How to pass arguments to construct from a phpspec?

by elise_daugherty , in category: PHP General , a year ago

How to pass arguments to construct from a phpspec?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a year ago

@elise_daugherty 

To pass arguments to the constructor of a class in phpspec, you can use the withArguments() method provided by phpspec.


Here's an example:


Let's assume you have a class MyClass with a constructor that expects two arguments:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class MyClass
{
    private $arg1;
    private $arg2;

    public function __construct($arg1, $arg2)
    {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
    }

    // ...
}


In your phpspec test, you can pass arguments to the constructor using the withArguments() method.

1
2
3
4
5
6
7
8
9
class MyClassSpec extends ObjectBehavior
{
    function it_initializes_with_arguments()
    {
        $this->beConstructedWith('arg1', 'arg2');

        // Your assertions here
    }
}


By calling the beConstructedWith() method and passing the required arguments, you are instructing phpspec to use these arguments when creating an instance of the class under test.


Remember to replace 'arg1' and 'arg2' with the appropriate arguments for your class.


This way, when you run phpspec, it will create an instance of the class MyClass using the specified arguments for the constructor.