纠缠:无法访问父作用域变量
Pester: Cannot access parent scoped variable
我在 Pester 中进行了以下简单测试:
# Name.Tests.ps1
$name = "foo"
Describe "Check name" {
It "should have the correct value" {
$name | Should -Be "foo"
}
}
因此,当我导航到包含测试脚本和 运行 Invoke-Pester
的文件夹时,我希望测试能够通过。相反,我收到以下错误:
[-]Check name.should have the correct value. Expected 'foo', but got $null...
知道为什么会失败以及为什么 $name
在 It
块中设置为 null - 不应该 $name
仍然设置为 foo
因为它来自父范围?
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.
因此,将变量赋值放在 BeforeAll
或 BeforeEach
中的 Describe
块中应该可以正常工作:
Describe "Check name" {
BeforeAll {
$name = "foo"
}
It "should have the correct value" {
$name | Should -Be "foo"
}
}
感谢@Mark Wragg 为我指明了正确的方向!
这是我必须做的:
#mine only happens during a foreach loop
$names = @("foo", "foo2")
Describe "Check name - all errors" {
foreach($rec in $names)
{
It "should have the correct value" {
$rec | Should -Be "foo"
}
}
}
#this is what i had to do to fix it :(
Describe "Check name - fixed" {
foreach($rec in $names)
{
It "should have the correct value" -TestCases @(
@{
rec = $rec
}
) {
$rec | Should -Be "foo"
}
}
}
我在 Pester 中进行了以下简单测试:
# Name.Tests.ps1
$name = "foo"
Describe "Check name" {
It "should have the correct value" {
$name | Should -Be "foo"
}
}
因此,当我导航到包含测试脚本和 运行 Invoke-Pester
的文件夹时,我希望测试能够通过。相反,我收到以下错误:
[-]Check name.should have the correct value. Expected 'foo', but got $null...
知道为什么会失败以及为什么 $name
在 It
块中设置为 null - 不应该 $name
仍然设置为 foo
因为它来自父范围?
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.
因此,将变量赋值放在 BeforeAll
或 BeforeEach
中的 Describe
块中应该可以正常工作:
Describe "Check name" {
BeforeAll {
$name = "foo"
}
It "should have the correct value" {
$name | Should -Be "foo"
}
}
感谢@Mark Wragg 为我指明了正确的方向!
这是我必须做的:
#mine only happens during a foreach loop
$names = @("foo", "foo2")
Describe "Check name - all errors" {
foreach($rec in $names)
{
It "should have the correct value" {
$rec | Should -Be "foo"
}
}
}
#this is what i had to do to fix it :(
Describe "Check name - fixed" {
foreach($rec in $names)
{
It "should have the correct value" -TestCases @(
@{
rec = $rec
}
) {
$rec | Should -Be "foo"
}
}
}