powershell - 纠缠:无法访问父作用域变量

标签 powershell scope pester

我在 Pester 中有以下简单的测试:

# Name.Tests.ps1

$name = "foo"

Describe "Check name" {
  It "should have the correct value" {
    $name | Should -Be "foo"
  }
}

所以当我导航到包含测试脚本的文件夹并运行 Invoke-Pester 时,我希望测试能够通过。相反,我收到以下错误:

[-]检查名称。应该有正确的值。预期为 'foo',但得到 $null...

知道为什么会失败以及为什么 $nameIt block 中设置为 null - 不应该仍然设置 $namefoo 因为它来自父范围?

最佳答案

Pester v5 需要遵循新规则,其中之一是以下 (https://github.com/pester/Pester#discovery--run):

Put all your code into It, BeforeAll, BeforeEach, AfterAll or AfterEach. Put no code directly into Describe, Context or on the top of your file, without wrapping it in one of these blocks, unless you have a good reason to do so. ... All misplaced code will run during Discovery, and its results won't be available during Run.

因此,将变量赋值放在 Describe block 内的 BeforeAllBeforeEach 中应该可以使其工作:

Describe "Check name" {
  BeforeAll {
    $name = "foo"
  }
  It "should have the correct value" {
    $name | Should -Be "foo"
  }
}

感谢@Mark Wragg 为我指明了正确的方向!

关于powershell - 纠缠:无法访问父作用域变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62539713/

相关文章:

powershell - 无法在自定义 Azure DSC 模块中找到类型 [CloudFileDirectory] ​​错误 - 相关程序集

windows - 如何在 Windows 上从 Powershell 打开文件夹(在我的桌面上)?

c++ - 错误 : 'current_millis' was not declared in this scope

javascript - 以函数作为对象成员的闭包

unit-testing - 模拟命令失败

unit-testing - 如何使用 Pester 模拟对 exe 文件的调用?

PowerShell - 如何使在模块内的函数中声明的变量可供调用脚本使用

powershell - 如何处理Powershell高级功能ErrorAction参数?

python - Python 嵌套函数中的变量作用域

powershell - 如何为多个小数点的值范围编写Pester单元测试