In my code snippet below or https://play.golang.org/p/tLld-zNF2zp, testValue
was declared inside Describe
block, changed in BeforeEach
block. Then, used in.
It
Expect
The test passes as expected. From the debug log, It
always shows testValue should be 0
instead of testValue should be
3
package awesomeProject1_test
import (
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("AwesomeProject1", func() {
var testValue int
BeforeEach(func() {
testValue = 3
})
Context("Correctness of testValue", func() {
It(fmt.Sprintf("testValue should be %d", testValue), func() {
Expect(testValue).To(Equal(3))
})
})
})
Why is testValue
not changed in It
statement but inside it?
CodePudding user response:
From ginkgo docs, another Describe
wraps Context
functions :
var _ = Describe("Book", func() {
var (
longBook Book
shortBook Book
)
BeforeEach(func() {
longBook = Book{
Title: "Les Miserables",
Author: "Victor Hugo",
Pages: 2783,
}
shortBook = Book{
Title: "Fox In Socks",
Author: "Dr. Seuss",
Pages: 24,
}
})
//Describe wrapping context
Describe("Categorizing book length", func() {
Context("With more than 300 pages", func() {
It("should be a novel", func() {
Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
})
})
Context("With fewer than 300 pages", func() {
It("should be a short story", func() {
Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
})
})
})
})
CodePudding user response:
package ginkgo_test
import (
"fmt"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("AwesomeProject1", func() {
var testValue int
BeforeEach(func() {
testValue = 3
})
Context("Correctness of testValue", func() {
It(fmt.Sprintf("testValue should be %d", testValue), func() {
Expect(testValue).To(Equal(3))
})
})
})
func TestGoStudy(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "GoStudy Suite")
}
=== RUN TestGoStudy
Running Suite: GoStudy Suite
============================
Random Seed: 1634629701
Will run 1 of 1 specs
•
Ran 1 of 1 Specs in 0.000 seconds
SUCCESS! -- 1 Passed | 0 Failed | 0 Pending | 0 Skipped
--- PASS: TestGoStudy (0.00s)
PASS
Process finished with the exit code 0
I have test your code and code worked well.
My test environment:
go version go1.17.1
github.com/onsi/ginkgo v1.16.5
github.com/onsi/gomega v1.16.0