I am looking for a way to reuse some stubs and mocks. I thought of encapsulating them inside a function. The advantage would be that I could modify that one function instead of modifying every single instance a function is being stubbed out separately. I think the issue has to do with how stub deals with the test environment. I am using mockery::stub.
Some example would be:
stub_some_function <- function(parent_function){
mockery::stub(
where = parent_function,
what = "content",
how = function(x, ...) TRUE
)
}
I could then have a test with a loop that calls the stubs I need (or do it inside a function and call that function):
add_2 <- function(x) x + 2
get_result <- function(x) add_2(x)
test_that("Returns TRUE", {
stub_some_function(get_result)
expect_true(get_result(4))
})
or with more stubs
add_2 <- function(x) x + 2
remove_4 <- function(x) x - 4
get_result <- function(x) {
res <- add_2(x)
remove_4(res)
}
stub_add_2 <- function(parent_function){
mockery::stub(
where = parent_function,
what = "add_2",
how = function(x, ...) TRUE
)
}
stub_remove_4 <- function(parent_function){
mockery::stub(
where = parent_function,
what = "remove_4",
how = function(x, ...) FALSE
)
}
stub_multiple(parent, ...){
dots <- list(...)
for (func in dots){
func(parent)
}
}
test_that("Returns FALSE", {
stub_multiple(get_result, stub_add_2, stub_remove_4)
expect_false(get_result(4)) # returns 2
})
Or even if I would call the stub_function(the_parent) inline as in:
test_that("Returns FALSE", {
stub_add_2(get_result)
stub_remove_4(get_result)
expect_false(get_result(4)) # returns 2
})
The test fails because the functions are not stubbed out.
I think one solution would be to have the whole test (test_that) inside a function itself so that mockery uses the test environment.