You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As you write more expectations, you might discover repeated code that you want to extract out in to a helper. For example, testthat has `expect_true()`, `expect_false()`, and `expect_null()` which are special cases of `expect_equal()`.
163
+
As you write more expectations, you might discover repeated code that you want to extract out in to a helper. Unfortunately creating helper functions is not straightforward in testthat because every `fail()` captures the calling environment in order to give maximally useful tracebacks. Because getting this right is not critical (you'll just get a slightly suboptimal traceback in the case of failure), we don't recommend bothering. However, we document it here because it's important to get it right in testthat itself.
You might wonder why these functions don't call `expect_equal()` directly. Unfortunately creating helper functions is not straightforward in testthat because every `fail()` captures the calling environment in order to give maximally useful tracebacks. Getting this right is not critical (you'll just get a slightly suboptimal traceback in the case of failure) but it's good practice, particularly for testthat itself.
181
-
182
-
To do things 100% correctly, in your helper function you need to have a `trace_env` argument that defaults to `caller_env()`, and then you need to pass it to every instance of
165
+
The key challenge is that `fail()` captures a `trace_env` which should be the execution environment of the expectation. This usually works, because the default value of `trace_env` is `caller_env()`. But when you introduce a helper, you'll need to explicitly pass it along:
183
166
184
167
```{r}
185
-
expect_waldo_equal_ <- function(
186
-
type,
187
-
act,
188
-
exp,
189
-
info,
190
-
...,
191
-
trace_env = caller_env()
192
-
) {
193
-
comp <- waldo_compare(
194
-
act$val,
195
-
exp$val,
196
-
...,
197
-
x_arg = "actual",
198
-
y_arg = "expected"
199
-
)
200
-
if (length(comp) != 0) {
201
-
msg <- sprintf(
202
-
"%s (%s) not %s to %s (%s).\n\n%s",
203
-
act$lab,
204
-
"`actual`",
205
-
type,
206
-
exp$lab,
207
-
"`expected`",
208
-
paste0(comp, collapse = "\n\n")
209
-
)
210
-
return(fail(msg, info = info, trace_env = trace_env))
168
+
expect_length_ <- function(act, n, trace_env = caller_env()) {
169
+
act_n <- length(act$val)
170
+
if (act_n != n) {
171
+
msg <- sprintf("%s has length %i, not length %i.", act$lab, act_n, n)
Note that the helper probably shouldn't be user facing, and we give it a `_` suffix to make that clear. It's also typically easiest for a helper to take the labelled value produced by `quasi_label()` rather than having to do that repeatedly.
0 commit comments