In v5 you can now also do it like this which is a bit more readable in my opinion:
BeforeDiscovery {
$listOfTags = @('BUSINESS-OWNER', 'COST-CENTER', 'LIFECYCLE1', 'APPLICATION', 'PROJECT-CODE', 'TECHNICAL-OWNER', 'BUDGET-CODE')
}
BeforeAll {
$resourceGroupName = 'DemoRG03032021'
$resourceGroup = Get-AzResourceGroup -Name $resourceGroupName
}
Describe "Resource Group" -ForEach $listOfTags {
It "$($resourceGroup.ResourceGroupName) has a $_ as tag" {
$resourceGroup.tags.keys -contains $_ | Should -Be $true
}
}
Edit: Putting the answer to your follow up question here as it's a lot more readable.
This is how I would personally organize the code you posted in the comments. I think adding another logical block makes sense, actually. If you put your other It statements inside of the block running with -Foreach
then you would run every new test once for every tag in $listOfTags
as well which is probably not what you want.
BeforeDiscovery {
$listOfTags = @('BUSINESS-OWNER', 'COST-CENTER', 'LIFECYCLE1', 'APPLICATION', 'PROJECT-CODE', 'TECHNICAL-OWNER', 'BUDGET-CODE')
}
Describe "Resource Group Tests" {
BeforeAll {
$resourceGroupName = 'TestResourceGroup203122021'
$resourceGroupLocation = 'eastus22222'
$resourceGroup = Get-AzResourceGroup -Name $resourceGroupName
}
Context "Resource Group Tags" -ForEach $listOfTags {
It "$($resourceGroup.ResourceGroupName) has a $_ as tag" {
$resourceGroup.tags.keys -contains $_ | Should -Be $true
}
}
Context "Resource Group Attributes" {
It "Resource Group $($resourceGroup.ResourceGroupName) Exists" {
$resourceGroup | Should -Not -BeNullOrEmpty
}
It "$($resourceGroup.ResourceGroupName) Location is $resourceGroupLocation" {
$($resourceGroup.Location) | Should -Be $resourceGroupLocation
}
}
}
Here is another way to think about it. If you wrote the following:
Foreach ($tag in $listOfTags){
Write-Host 'do this thing for each tag'
Write-Host 'do this thing once'
}
Imagine each Write-Host is your It statement. You don't want that second statement inside of the same context as the other, because you don't want it to run once for every value in $listOfTags
. You logically separate it with a new Describe or Context block.