Running jobs in clean sessions is a great to test code in isolation without having to launch new RStudio applications.

## Case: forgot to rename a variable

Here’s an embarrassing error I commit too often: Say I want to write a function that computes the Mean Squared Error (MSE) of a numerical vector. First, I fiddle around with it in the console, ending up with:

tmp = rnorm(1000, sd = 2)
mean((tmp - mean(tmp))^2)
## [1] 4.016175

It works! Then I wrap the code in a function and try it out:

mse = function(x) {
mean((tmp - mean(tmp))^2)
}

mse(rnorm(1000, sd = 1))
## [1] 4.016175

Huh!? It runs but the MSE should be around 1 here, not 4.

## Solution: fast debugging with job::empty()

You can select the code and click the addin “Run selection as job in empty session”. Or you can do the exact same action using code via job::empty():

job::empty({
mse = function(x) {
mean((tmp - mean(tmp))^2)
}

mse(rnorm(1000, sd = 1))
})

In the job, you’ll see the error message:

#> Error in mean((tmp - mean(tmp))^2) : object 'tmp' not found 

Aha, by running the code in a separate session, we learned that it only seemed to work because I had the tmp variable lingering in my environment. Errors like this become less trivial as the code (and your environment) grows more complex.

## Selective import

In the example above, you can, of course, import selectively too. These two jobs are identical, but I prefer the first.

# Add to empty
job::empty({
mse(rnorm(1000, sd = 1))
}, import = c(mse))

# Avoid from full
job::job({
mse(rnorm(1000, sd = 1))
}, import = c(mse), packages = NULL, opts = NULL)

## testthat unit tests

testthat unit tests have access to your current environment so it is prone to the kind of errors introduced above. job::empty() to the rescue:

job::empty({devtools::test()})
job::empty({devtools::check()})  # while we're at it

This also frees up your console in the meantime.