这是我所拥有的:
spec :: Spec
spec = do
manager <- runIO newManager
it "foo" $ do
-- code that uses manager
it "bar" $ do
-- code that usees manager
runIO
的文档建议我应该使用 beforeAll
相反,因为我不需要 manager
要构建规范树,我只需要它来运行每个测试,在我的用例中,最好让它们共享同一个管理器,而不是为每个测试创建一个新管理器。If you do not need the result of the IO action to construct the spec tree, beforeAll may be more suitable for your use case.
beforeAll :: IO a -> SpecWith a -> Spec
但我不知道如何从测试中访问经理。
spec :: Spec
spec = beforeAll newManager go
go :: SpecWith Manager
go = do
it "foo" $ do
-- needs "manager" in scope
it "bar" $ do
-- needs "manager" in scope
最佳答案
规范参数作为常规函数参数传递给您的 it block (如果您想了解发生了什么,请查看 Example
类型类的关联类型)。一个完全独立的例子是:
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = beforeAll (return "foo") $ do
describe "something" $ do
it "some behavior" $ \xs -> do
xs `shouldBe` "foo"
it "some other behavior" $ \xs -> do
xs `shouldBe` "foo"
关于unit-testing - 在测试期间访问由 `beforeAll` 设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536294/