2

我正在使用 Speclj 为 Clojure 应用程序编写测试。我习惯于在 BDD 中做这样的事情:

context "some context"
  stub my-function :return true
  it "has behavior one"
    should true my-function
  it "has behavior two"
    should_not false my-function

但是在 Speclj 中,我似乎找不到如何在特征之间共享存根的示例,所以我目前一直在编写这样的代码:

(describe "this"
  (context "that"
    (it "accepts nil"
      (with-redefs [called-fn (constantly nil)]
          (should= nil (my-fn nil)))))
    (it "accepts 1"
      (with-redefs [called-fn (constantly nil)]
          (should= 100 (my-fn 1))))))

(我意识到这是一个有点人为的例子,可以说这些断言都可以归于一个特征,但现在让我们假设我有充分的理由编写这样的代码。)

但是,我希望只需要存根called-fn一次,但是将其移出its 会引发错误,因为called-fn调用的是实数而不是我的重定义。

有没有办法在 Speclj 中重用 redefs(或使用 Speclj 存根),这样我就不会被困在特征内将它们全部向下推?

4

1 回答 1

4

您可以使用around宏来完成此操作。

这是一个示例规范:

(ns sample.core-spec
  (:require [speclj.core :refer :all]
            [sample.core :refer :all]))

(describe "a test"
  (it "returns output from fn-a"
    (should= 1 (fn-b)))

  (describe "using with-redef"
    (around [it] (with-redefs [fn-a (fn [] 2)] (it)))

    (it "returns the output from redefined function"
      (should= 2 (fn-b)))))

资源:

(ns sample.core)

(defn fn-a []
  1)

(defn fn-b []
  (fn-a))
于 2014-04-17T19:45:15.417 回答