Strange behaviour when stubbing R6 classes in global environment - stub affects non-stubbed functions
andrewl776 opened this issue · comments
Andrew Little commented
library(R6)
library(mockery)
library(openxlsx)
# Define public function
some_function = function() {
cat("something")
}
# Define class "some_class"
some_class = R6Class("some_class",
public = list(
some_method = function() {return(some_function())},
other_method = function() {return('method in class')}
)
)
# Check we can initialise class and call method
obj = some_class$new()
obj$some_method() #works
#> something
# Now we stub the method `some_method`, but with a function that we don't even
# call in the method - "hi"
# This works inside a local(), but not outside...
local({
stub(obj$some_method, 'hi', function() NULL)
wb <- createWorkbook()
addWorksheet(wb, "sheet1")
writeData(wb, sheet = "sheet1", x = mtcars)
saveWorkbook(wb, "test.xlsx", overwrite = TRUE) ## works inside local
})
unlink("test.xlsx")
# Doesn't work outside of local({})
stub(obj$some_method, 'hi', function() NULL)
wb <- createWorkbook()
addWorksheet(wb, "sheet1")
writeData(wb, sheet = "sheet1", x = mtcars)
saveWorkbook(wb, "test.xlsx", overwrite = TRUE) ## works inside local
#> Error in write_worksheet_xml(prior = prior, post = post, sheet_data = ws$sheet_data, : Evaluation error: <text>:1:28: unexpected '<'
#> 1: new("Sheet_Data", .xData = <
#> ^.
Created on 2022-01-19 by the reprex package (v2.0.1)
Hadley Wickham commented
mockery is no longer under active development as we now recommend testthat::local_mocked_bindings()
. That doesn't yet support mocking R6 methods, but I've added an issue to look into it: r-lib/testthat#1892.
Hadley Wickham commented
mockery is no longer under active development as we now recommend testthat::local_mocked_bindings()
. That doesn't yet support mocking R6 methods, but I've added an issue to look into it: r-lib/testthat#1892.
Andrew Little commented
Thanks a lot!