在speclj上下文中重用stub / redef

时间:2014-04-17 18:32:06

标签: clojure bdd speclj

我正在使用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存储一次,但是将其从it移出会引发错误,因为真正的called-fn会被调用而不是我的redef。

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

1 个答案:

答案 0 :(得分: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))