Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strange behaviour when stubbing R6 classes in global environment - stub affects non-stubbed functions #58

Closed
andrewl776 opened this issue Jan 19, 2022 · 3 comments

Comments

@andrewl776
Copy link

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
Copy link
Member

hadley commented Oct 31, 2023

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 hadley closed this as completed Oct 31, 2023
@hadley
Copy link
Member

hadley commented Oct 31, 2023

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.

@andrewravelin
Copy link

Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants