How do I share variables across run and discovery?

I want to declare some variables and use them in

  • It blocks
  • values for -ForEach
  • mocks defined inside BeforeAll/BeforeEach

This is my initial script. Only the first test passes.

BeforeAll {
    function MockableFunction {}
}

Describe "Root" {

    BeforeDiscovery {

        $sharedVariable = "hello"
    
    }

    BeforeAll {

        Mock MockableFunction {
            return $sharedVariable
        }

    }

    It "should see the shared variable in ForEach" -ForEach @($sharedVariable) {

        $_ | Should -Be "hello"

    }

    It "should see the shared variable in the script body" {

        $sharedVariable | Should -Be "hello"

    }

    It "should see the shared variable in a mock created in BeforeAll" {

        (MockableFunction) | Should -Be "hello"

    }

}

UPDATE: my original workaround was dot-sourcing a global function into both BeforeDiscovery and BeforeAll, however that crashed Pester when multiple test files tried to do the same (probably due to name collision in the global scope). The new workaround is to put the variables in a separate file and dot-source that:

# MyComponent.Tests.variables.ps1
$sharedVariable = "hello"
# MyComponent.Tests.ps1

BeforeAll {
    function MockableFunction {}
}

Describe "Root" {

    BeforeDiscovery {

        . $PSCommandPath.Replace('.ps1', '.variables.ps1')
    
    }

    BeforeAll {

        . $PSCommandPath.Replace('.ps1', '.variables.ps1')

        Mock MockableFunction {
            return $sharedVariable
        }

    }

    It "should see the shared variable in ForEach" -ForEach @($sharedVariable) {

        $_ | Should -Be "hello"

    }

    It "should see the shared variable in the script body" {

        $sharedVariable | Should -Be "hello"

    }

    It "should see the shared variable in a mock created in BeforeAll" {

        (MockableFunction) | Should -Be "hello"

    }

}

Is there a better way to do this?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.