gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:56:29 25 4
gpt4 key购买 nike

我在 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 orAfterEach. Put no code directly into Describe, Context or on the topof your file, without wrapping it in one of these blocks, unless youhave a good reason to do so....All misplaced code will run during Discovery, and its results won't beavailable 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com