onsi / ginkgo

A Modern Testing Framework for Go
http://onsi.github.io/ginkgo/
MIT License
8.08k stars 643 forks source link

It function use only check last test case param #1430

Closed RedCrazyGhost closed 2 weeks ago

RedCrazyGhost commented 2 weeks ago

@onsi Can you help me? look this issue

package main

import (
    "context"
    "fmt"

    . "github.com/onsi/ginkgo/v2"
    . "github.com/onsi/gomega"
)

type TestCase struct {
    ...
}

var _ = Describe("test parse services", func() {
  cases := []TestCase{
         {...},
         {...},
         {...},    <<<--- only check this
  }
  for _, c := range cases {
  Context(c.name, func() {
    It("should return the expected results for "+c.name, func() {
        /// checking 
    })
  })
}
blgm commented 2 weeks ago

Hi @RedCrazyGhost there's a section in the docs about this: https://onsi.github.io/ginkgo/#dynamically-generating-specs

My guess is that you've hit a common Go gotcha relating to variables in loops; more details here: https://go.dev/blog/loopvar-preview

A couple of things to try are to copy c as suggested in the docs:

for _, c := range cases {
  c := c
  Context(c.name, func() {
    It("should return the expected results for "+c.name, func() {
        /// checking 
    })
  })

Or an anonymous function can have the same effect:

    for _, c := range cases {
        func (c struct{name string}) {
            Context(c.name, func () {
                It("should return the expected results for "+c.name, func () {
                    /// checking
                })
            })
        }(c)
    }