DMA's avatar
Level 2

PHPSpec shouldBeCalled within the method under test

First, I may be going about this the wrong way entirely but here goes..

Here's the test I'm trying to write:

Given I have productA, called 'Jeans' with a slug 'jeans'
And I have productB, which is also called 'Jeans'
When I generate a slug for productB
Then then an exception is thrown

In my class, I'm using a repository to perform the check if the slug already exists, but I don't want my test to actually call the method on the repository that gets injected to the class.

So, here is where I am so far:

function it_should_generate_a_unique_slug(Product $productA)
    {
        // The mock that is injected
        $productA->name = 'Jeans';
        // 1) I want to also specify what should be returned
        // 2) I don't want the generateSlug method to actually be called, as it would fire a db request because of the repository that it uses
            $productA->generateSlug('Jeans')->shouldBeCalled();

        // The class under test
        $this->name = 'Jeans';
// 3) This doesn't work at all, but hopefully describes what I want to achieve      $this->countExistingProductsWithSlug('jeans')->shouldBeCalled()->duringGenerateSlug('Jeans')->shouldReturn(1);

    }

I want to make sure that when one slug is set with 'jeans', another object cannot run the generateSlug method and return the same value.

The code in the Product class is:

public function generateSlug($fromText)
    {
        // Convert the text to lower case and replace spaces
        $slug = str_replace(' ', '-', strtolower($fromText));
        // Strip out any none alphanumeric characters
        $slug = preg_replace("/[^a-z0-9_\s-]/", "", $slug);
        // Trim the length of the slug
        $slug = substr($slug, 0, 100);

        // Ensure the slug is unique
        if($this->repository->countExistingProductsWithSlug($slug) > 0)
        {
            throw new Exception('The slug generated must be unique.');
        }

        return $slug;
    }

How can I write the test without the repo method actually being hit?

0 likes
0 replies

Please or to participate in this conversation.