[NoBrainer] ‘The Should command may only be used inside a Describe block’ when run in an interactive PowerShell session

Here is a small helper method that you can use when creating Pester tests and trying to run them in an interactive PowerShell session.

When executing statements that include the Pester Should Cmdlet interactively in a PowerShell session you receive the following error message:

PS > $Host.Name | Should Be 'ConsoleHost'
The Should command may only be used inside a Describe block.
At C:\Program Files\WindowsPowerShell\Modules\Pester\Functions\Describe.ps1:125 char:9
+         throw "The $CommandName command may only be used inside a Describe block ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (The Should comm...Describe block.:String) [], RuntimeException
    + FullyQualifiedErrorId : The Should command may only be used inside a Describe block.

With the Should helper method below you can still execute the original Pester statement without having to cut away the Pester part. It will instead show you the data type of the expression and its content along with the full Pester expression. So if you executed the same statement from above with the helper function loaded, you would receive the following output:

PS > $Host.Name | Should Be 'ConsoleHost'
$Host.Name | Should Be 'ConsoleHost'

Asserted type: 'System.String'

Asserted content:
###
ConsoleHost
###

All you have to do is to import the function in your PowerShell session. Keep in mind that if you later load the Pester module (either explicitly via Import-Module or implicitly via using one of its Cmdlets) the original Pester Should Cmdlet will shadow your helper definition. You would then have to import the script once more.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: