Skip to content

Accessing the test name from within the test subroutine #41

@billmatzen

Description

@billmatzen

I'm finding the Test::Spec module very useful, but I've been trying to find a way to access the test name from within the test subroutine, but have so far been unable to find a good way. I was hoping to find a magic variable being passed to the subroutine or a global value holding the current test case, but haven't found anything. My purpose would be for error logging from within the test case code (such as beginning, end, and just for general context).

I realize I could do the following, but 'd like to avoid repeating the test case name in every case:

it "My Test Name" => sub {
    my $test_case_name = "My Test Name";
    print "ENTER $test_case_name\n";
    ok(1);
    print "EXIT  $test_case_name\n";
};

ENTER My Test Name
ok 1 - My Test Name 
EXIT  My Test Name

I tried the following, but if there are multiple tests that all use the same file scope variable (as below), the value at runtime is the last value it was set to ("My Test Name 2"), so that doesn't work very well.

my $test_case_name = "My Test Name 1";
it $test_case_name => sub {
    print "ENTER $test_case_name\n";
    ok(1);
    print "EXIT  $test_case_name\n";
};

$test_case_name = "My Test Name 2";
it $test_case_name => sub {
    print "ENTER $test_case_name\n";
    ok(1);
    print "EXIT  $test_case_name\n";
};

ENTER **My Test Name 2**
ok 1 - My Test Name 1
EXIT  **My Test Name 2**
ENTER My Test Name 2
ok 2 - My Test Name 2
EXIT  My Test Name 2

Thanks for any advice, or if this is a feature request, let me know how to submit that.

Thanks,
Bill

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions