Search code examples
phpbddphpspec

PHPSpec should return correct value


I have problem with phpspec function - shouldReturn. I have factory whitch creating image object and I want to testing that factory.

public function create($imageParams)
{
  $image = new Image;
  $image->setName($imagesParams['name']);
  return $image;
}

phpspec:

public function it_create_image_object()
{
  $image = new Image;
  $image->setName('Example Name');
  $imageParams = ['name'=>'Example Name'];
  $this->create($imageParams)->shouldReturn($image);

}

PHPSpec throw Exception : it create image object expected [obj:App\ImagesBundle\Entity\Images], but got [obj:AppImagesBundle\Entity\Images].

Why PHPSpec throwing exception instead return green light?


Solution

  • The spec class will never work as you cannot stub an object that is instantiated in the spec'ed class. In your spec test you have to check for the returned type and for the values, like so:

    public function it_create_image_object()
    {
      $imageParams = ['name'=>'Example Name'];
      $image = $this->create($imageParams);
    
      $image->getName()->shouldReturn('Example Name');
      $image->shouldHaveType('App\ImagesBundle\Entity\Images');
    }