Skip to content

Commit 7b0d8b5

Browse files
committed
add Binding example to Global and local bindings
1 parent 29b047f commit 7b0d8b5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

content/documentation/global-and-local-bindings.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,29 @@ To update a variable with a function the `swap!` function can be used.
6969
(swap! foo + 2) # Evaluates to 12
7070
(deref foo) # Evaluates to 12
7171
```
72+
73+
## Binding
74+
75+
While writing tests on code depending on external state can be challenging, `binding` function allows to remap existing bindings which can be used for mocking functions or values during tests. As example, code depending on runtime environment:
76+
77+
```phel
78+
(ns my-app\tests\demo
79+
(:require phel\test :refer [deftest is]))
80+
81+
# Function that would return e.g. "x86_64", depending on the environment:
82+
(defn get-system-architecture [] (php/php_uname "m"))
83+
84+
(defn greet-user-by-architecture []
85+
(print "Hello" (get-system-architecture) "user!"))
86+
87+
# With binding, a mock function can be used in place of the original one
88+
# allowing to write tests for cases that depend on system state:
89+
(deftest greeting-test
90+
(binding [get-system-architecture |(str "i386")] # <- mock function
91+
(let [greeting-out (with-output-buffer (greet-user-by-architecture))]
92+
(is (= "Hello i386 user!" greeting-out)
93+
"i386 system user is greeted accordingly"))))
94+
95+
# Test is successful:
96+
# ✔ greet-test: i386 system user is greeted accordingly
97+
```

0 commit comments

Comments
 (0)