testthat different interactive vs terminal

Viewed 20

Hit a weird quirk of R and testthat, wondering whether anyone can explain it? I have found that testthat seems to give different results depending on whether it is run interactively or on the terminal?

An example is create a file example_funcs.R

function_main <- function(df, avg_gear = NA) {
  
  function_main2(df, avg_gear)
  
}

function_main2 <- function(data_df, avg_gear) {
  
  
  data_df$car_name = row.names(data_df)
  
  get_avg_gear(data_df)
  
}

# This function is missing an argument 
get_avg_gear <- function(data_df) {
  
  data_df %>%
    filter(gear == avg_gear)
  
}

Then create a second file called example.R

library(dplyr)
source("example_funcs.R")

data_df = mtcars

avg_gear = median(data_df$gear)

test_that("example", {
  
  output = function_main(data_df, avg_gear = avg_gear)
  
  expect_true(
    all(output$gear == 4)
  )
  
})

If you run

> testthat::test_file("example.R")

══ Testing example.R ═══════════════════════════════════════════════════════════════════════════════════════
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 1 ] Done!

You see it passes. However in a terminal with the identical command (using GitBash terminal in RStudio)

$ Rscript -e ' testthat::test_file("example.R")'

══ Testing example.R ═══════════════════════════════════════════════════════════════════════════════════════════════════════════[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]

── Error (example.R:11:3): example ─────────────────────────────────────────────
Error in `filter(., gear == avg_gear)`: Problem while computing `..1 = gear == avg_gear`.
Caused by error:
! object 'avg_gear' not found
Backtrace:
  1. global function_main(data_df, avg_gear = avg_gear)
       at example.R:11:2
  6. dplyr:::filter.data.frame(., gear == avg_gear)
  7. dplyr:::filter_rows(.data, ..., caller_env = caller_env())
  8. dplyr:::filter_eval(dots, mask = mask, error_call = error_call)
 10. mask$eval_all_filter(dots, env_filter)

[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]

It now fails?

I can't think why that would be? The error is caused by a missing function argument, but R lexical scoping rules should cover it I think

First, R looks inside the current function. Then, it looks where that function was defined (and so on, all the way up to the global environment). Finally, it looks in other loaded packages. Advanced R

0 Answers
Related