r-lib / testthat

An R 📦 to make testing 😀
https://testthat.r-lib.org
Other
868 stars 313 forks source link

`testthat::test_file` prevents `testthat::it` from accessing global variables #1926

Open TymekDev opened 4 months ago

TymekDev commented 4 months ago

Hi, I just noticed that code inside testthat::it (specifically with testthat::) does not have access to global variables when invoked with testthat::test_file() (or other runners). Sourcing the same file works fine. Using library(testthat) and just it works fine too. See examples below.

testthat version: 3.2.0

library variant

File

# reprex_library.R
library(testthat)
x <- "asdf"
describe("a", {
  it("b", {
    force(x)
  })
})

Output

source("reprex_library.R")
# Test passed 🌈

testthat::test_file("reprex_library.R")
# ══ Testing reprex_library.R ═══════════════
# [ FAIL 0 | WARN 0 | SKIP 0 | PASS 0 ] Done!

:: variant

File

# reprex_colons.R
x <- "asdf"
testthat::describe("a", {
  testthat::it("b", {
    force(x)
  })
})

Output

source("reprex_colons.R")
# Test passed 🎊

testthat::test_file("reprex_colons.R")
# ══ Testing reprex_colons.R ══════════════════
# [ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]
# 
# ── Error (reprex_colons.R:4:5): b ───────────
# Error in `force(x)`: object 'x' not found
# Backtrace:
#     ▆
#  1. └─base::force(x) at reprex_colons.R:4:5
# [ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]