Skip to content

v5: BeforeEach/AfterEach -Context? #1219

Description

@nvarscar

1. General summary of the issue

I tend to write a chain of different It tests that expect a certain resource to be available during the whole execution of the Context in persistent state and then get removed once the tests in this particular context are over. Right now, I'm using BeforeAll and AfterAll for each Context to create/remove such resources. It would be much easier to have a BeforeEach -Context so that I could define it on a Describe level just once.

2. Describe Your Environment

Powershell 5.1/Core, Windows and Linux

3. Desired Behavior

Describe "my tests" {
  BeforeEach -Context {
    # create new file here
  }
  AfterEach -Context {
    # remove file here
  }
  Context "context 1" {
    It "it 1" {
      # doing some activities on the file
      $true | Should -Be $true
    }
    It "it 2" {
      # continuing working on the same file and expecting it to have results from "it 1"
      $true | Should -Be $true
    }
  }
  Context "context 2" {
    It "it 1" {
      # doing some activities on the file
      $true | Should -Be $true
    }
    It "it 2" {
      # continuing working on the same file and expecting it to have results from "it 1"
      $true | Should -Be $true
    }
  }
}

4.Current Behavior

Describe "my tests" {
  Context "context 1" {
    BeforeAll {
      # create new file here
    }
    AfterAll {
      # remove file here
    }
    It "it 1" {
      # doing some activities on the file
      $true | Should -Be $true
    }
    It "it 2" {
      # continuing working on the same file and expecting it to have results from "it 1"
      $true | Should -Be $true
    }
  }
  Context "context 2" {
    # defining all the same logic again
    BeforeAll {
      # create new file here again
    }
    AfterAll {
      # remove file here again
    }
    It "it 1" {
      # doing some activities on the file
      $true | Should -Be $true
    }
    It "it 2" {
      # continuing working on the same file and expecting it to have results from "it 1"
      $true | Should -Be $true
    }
  }
}

5. Possible Solution

As suggested, add something like a -Context switch to the BeforeEach/AfterEach blocks so that they only trigger on Contexts

6. Context

Want to get rid of excessive code and making changes on 10 different places instead of a single block.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions