<p>I'm rewriting unit test of our k8s controller with ginkgo.</p>

<p>As previous TDD, for each test, we will have something like.</p>

<pre class="lang-golang prettyprint-override"><code>    // Create the Channel  object and expect the Reconcile
    g.Expect(c.Create(context.TODO(), myObj)).NotTo(gomega.HaveOccurred())
    defer c.Delete(context.TODO(),myObj)
</code></pre>

<p>What we want is, create an object for a test and delete it from the underline cluster after this test.</p>

<p>Now, on <code>ginkgo</code>, we are running tests within <code>spec</code> of containers. To me the <code>container</code> is the origin process, if that's the case does it mean the <code>defer</code> defined within the <code>It</code> spec will execute before exiting <code>container</code> instead of exiting the <code>It</code> spec.</p>

<p>For example,</p>

<pre class="lang-golang prettyprint-override"><code>var _ = Describe("my desr", func(){
   It("a", func(){
     fmt.Println(100)
     defer func(){fmt.Println("a", 100)}()
   })

   It("b", func(){
     fmt.Println(200)
     defer func(){fmt.Println("b", 200)}()
  })
})
</code></pre>

<p>Would the result be:</p>

<p><strong>a</strong></p>

<pre><code>100
a100
200
b200
</code></pre>

<p>Or </p>

<p><strong>b</strong></p>

<pre><code>100
200
b200
a100
</code></pre>

<p>In my case, I definitely what the first behavior. Or I'm in the wrong direction in terms of getting the <code>defer</code> behavior? I mean, should I look into the <code>BeforeEach</code> and <code>AfterEach</code> approach?</p>

Ian Zhang
<p>You would see the first behavior, because the enclosing scope of the <code>defer</code>s is the same anonymous function as the previous <code>Println</code>. <code>defer</code>red functions get called when exiting the scope.</p>
