1

I am at the last stages with my pester tests, but am having issues with the variable scoping. I have quite a few tests and would like use something like Global scoping in order to declare variables such as $ModuleName, $ProjectRoot, and other similar things that are needed in each test.

I have tried using New-Variable -Scope Global and $Global:ModuleName but these don't seem to be visible in the Pester Tests.

I am calling Invoke-Pester from a build.ps1 file which has these declared.

Has anyone seen any good ways to use centrally defined variables, without using $env: variables?

Josh Wright
  • 422
  • 3
  • 12
  • Please edit your question to include a [mcve]. – zett42 Jan 08 '21 at 11:15
  • Just put them in a ps1 and dot source that script in all pester tests. You could also pass them as script variables from the build.ps1 to the test scripts – mhu Jan 08 '21 at 12:39
  • I have since gone for the approach used in the BuildHelpers Module and am now using $Env:BH variables that are initialised in the build.ps1 script. I now place $Env variables in the BeforeAll block and assign them to $Script: variables for use later in the Test. – Josh Wright Jan 08 '21 at 12:43

1 Answers1

2

I have found using $Env: variables to be the best approach. Thanks to the BuildHelpers module for showing me this.

This is now what the beginning of my Pester Test looks like:

Describe "Core Module Validation" {
BeforeAll {
    $Script:moduleName = $ENV:BHProjectName
    $Script:modulePath = $ENV:BHModulePath

    Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue

    $Script:manifestTestResult = Test-ModuleManifest -Path $Env:BHPSModuleManifest
    $Script:publicScriptFiles = Get-ChildItem -Path "$modulePath\Public" -Recurse
}

It "should cleanly import Module '$ENV:BHProjectName'" {
    { Import-Module -Name $modulePath -Force } | Should -Not -Throw
}
It "should export one or more functions" {
    Import-Module -Name $modulePath -Force
    Get-Command -Module $moduleName | Measure-Object | Select-Object -ExpandProperty Count | Should -BeGreaterThan 0
}

It "should have a valid PSD1 Module Manifest" {
    { Test-ModuleManifest -Path $ENV:BHPSModuleManifest } | Should -Not -Throw
}

These $Env: variables are set in my build.ps1 file, and are only temporary for the session.

Josh Wright
  • 422
  • 3
  • 12
  • Your `$Script:moduleName` really helped me out to define variables. I assume it is powershell related on specific for pester, right? – tomwaitforitmy Apr 12 '23 at 14:36
  • Great to hear! Yes, it is a variable scope in PowerShell, nothing to do with Pester. [about_Scopes - PowerShell scopes](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.3#powershell-scopes) – Josh Wright Apr 15 '23 at 13:57