param (
[Parameter()]
$ParameterPath = "Approved-rule.json"
)
# BeforeDiscovery {
# ## Store the data from the json file to be re-used
# $parameterFile = Get-Content $ParameterPath
# }
Describe "Rules validation (Base)" -Tag "CI" {
BeforeAll {
$parameterFile = Get-Content $ParameterPath
$incommingParamObject = $parameterFile.Parameters
$rules = $parameterFile.Parameters.Test.value
}
Context "Validate for Parameter" {
It "File should not be null or empty" {
Write-Host "rule: $($rules)"
$rules | Should -Not -BeNullOrEmpty
}
}
}
When i am running the pester script the rule is coming as empty value. How does the scoping in pester works does the BeforeAll block be a global or i should add BeforeDiscovery?
Another question where should I add a Inline function ?
When running the above pester code all the variables are getting printed null. The file exists with correct path.
Solution:
To resolve this issue, you should define your functions in the appropriate block based on where you need to use them. If you need to use a function/varaible in an It block, you should define it in a BeforeAll block. If you need to use a function in a Describe or Context block, you should define it in a BeforeDiscovery block.
You have a typo in your It
statement, should be $rules
instead of $rule
and you're missing ConvertFrom-Json
in your BeforeAll
block, then your code should work fine.
Using this Json as an example:
Approved-rule.json
{
"Parameters": {
"Test": {
"value" : [
"foo",
"bar",
"baz"
]
}
}
}
And the Pester test code:
param (
[Parameter()]
$ParameterPath = 'Approved-rule.json'
)
Describe 'Rules validation (Base)' -Tag 'CI' {
BeforeAll {
$parameterFile = Get-Content $ParameterPath | ConvertFrom-Json
$incommingParamObject = $parameterFile.Parameters
$rules = $parameterFile.Parameters.Test.value
}
Context 'Validate for Parameter' {
It 'File should not be null or empty' {
Write-Host "rule: $($rules)"
$rules | Should -Not -BeNullOrEmpty
}
}
}
When running you can get:
Starting discovery in 1 files.
Discovery found 1 tests in 75ms.
Running tests.
rule: foo bar baz
[+] C:\Users\User\Documents\pwsh\Pester.test.ps1 240ms (65ms|103ms)
Tests completed in 250ms
Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0