lundi 28 janvier 2019

How do we test for an optional hash field using Test2::V0

I am trying to work out how to test for an optional hash field using Test2::V0. I currently have the following:

use 5.016;
use Test2::V0;

subtest 'optional fields in a hash' => sub {
    my $check = hash {
        field foo => qr/^[0-9]+$/;
        field bar => qr/^[a-zA-Z]+$/; # this field is optional
    };

    like(
        { foo => 1 },
        $check,
        'should pass when optional field is omitted',
    );

    like(
        { foo => 2, bar => 'a' },
        $check,
        'should pass when optional field is provided',
    );
};

done_testing;

Now if I drop the check for the optional field:

my $check = hash {
    field foo => qr/^[0-9]+$/;
    # field bar => qr/^[a-zA-Z]+$/; # this field is optional
};

the test will pass. But I want to test the value when it's there.

Any ideas?

Aucun commentaire:

Enregistrer un commentaire