[英]Match “any string” in Haskell record in HSpec test
我有一個數據類Entity
,其定義如下:
data Entity = Entity { id :: String, name :: String }
和一個返回IO Entity
的函數:
newPersistentEntity :: String -> IO Entity
我想為此編寫一個HSpec測試:
spec :: Spec
spec = describe "newPersistentEntity function" $
it "returns a new Entity with a generated id and the specified name" $
newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}
問題是該ID是數據庫生成的UUID。 我想斷言id
是使測試通過的字符串。
我該如何實現?
您可以創建記錄,然后使用其id
值來創建要進行比較的記錄嗎? 就像是:
new <- newPersistentEntity "myName"
new `shouldBe` Entity { id = (id new), name = "myName" }
(注意:沒有足夠的信息來測試此代碼,請將其視為偽代碼)。
附帶一提,您的代碼看起來不像普通的持久性代碼,因此我假設您使用的是其他庫。
Entity
的id
不能為String
,因為是靜態類型。 但是您可能確實想強制對其進行評估,以確保它不是最底層的。
spec :: Spec
spec = describe "newPersistentEntity function" $
it "returns a new Entity with a generated id and the specified name" $ do
x <- newPersistentEntity "myName"
pure $! id x -- Force evaluation of the `id` field to ensure that
-- the database actually did return a string here
name x `shouldBe` "myName"
我實際上以一種不同的方式解決了這個問題,在這里我將針對上下文進行說明。 您可能不應該使用它,因為可接受的答案更容易理解且不太冗長。
spec :: Spec
spec = describe "newPersistentEntity function" $
it "returns a new Entity with a generated id and the specified name" $
newPersistentEntity "myName" >>= (`shouldSatisfy` (\case
Entity {id = _, name = "myName"} -> True
_ -> False))
但是,要使它起作用,您還需要應用lamda大小寫語言擴展名:
{-# LANGUAGE LambdaCase #-}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.