Skip to content
This repository has been archived by the owner on Jun 16, 2021. It is now read-only.

Adds a sequence method for traversable values #9

Merged
merged 5 commits into from
May 18, 2021

Conversation

lukeraymonddowning
Copy link
Member

@lukeraymonddowning lukeraymonddowning commented May 14, 2021

Me again!

Part two of my little ballet of code is the sequence method. Imagine that you have a traversable array or collection and you want to check that each item sequentially follows a set of assertions.

I often need this kind of functionality when I'm dealing with mocked responses, and I want to make sure that the values returned in a collection of objects match the mock.

Here's an example of the usage:

/**
 * The mocked UserImporter class returns 3 user objects.
 * The first user is called Luke, the second Nuno and 
 * the third Taylor. We want to check they've 
 * actually been imported as expected.
 */
$users = resolve(UserImporter::class)->import(); 

expect($users->map->name)->sequence(
    fn($expect) => $expect->toEqual('Luke'),
    fn($expect) => $expect->toEqual('Nuno'),
    fn($expect) => $expect->toEqual('Taylor'),
);

If you like this and feel it warrants becoming part of the expectation API, there is a point of discussion, which is "should a BedMethodCall exception be thrown if the number of items in the traversable is less than the number of declared sequence items?"

Have a great weekend!

@lukeraymonddowning
Copy link
Member Author

There is another option here in that instead of a sequence method we could simply allow a varadic number of closures to the each method...

@nunomaduro
Copy link
Member

Still ensure about the naming on this one.

@lukeraymonddowning
Copy link
Member Author

Open to other names!

I took inspiration for the sequence name from here: https://laravel.com/docs/http-client#faking-response-sequences

@nunomaduro
Copy link
Member

That helps - so should we go for:

expect([1, 2])->each->sequence(
    fn($number) => $number->toEqual(1),
    fn($number) => $number->toEqual(2),
);

Or:

expect([1, 2])->sequence(
    fn($number) => $number->toEqual(1),
    fn($number) => $number->toEqual(2),
);

@lukeraymonddowning
Copy link
Member Author

Actually, I really like it chained to each. Refactored to that.

@lukeraymonddowning
Copy link
Member Author

This now allows for:

expect([1, 2, 3])
    ->each->toBeInt()
    ->sequence(
        fn($expect) => $expect->toBe(1),
        fn($expect) => $expect->toBe(2),
        fn($expect) => $expect->toBe(3)
    );

@nunomaduro nunomaduro merged commit c1e2139 into pestphp:master May 18, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants