Search code examples
rtestingtestthat

testthat: Expect error and variable value at once?


I want to test a function that can throw an error but I also want to ensure that a variable value is correct (to verify the expected last state before the error - so I want to test for unwanted side effects). Is it possible to do this?

Simplified expression to be tested

x <- 1    # could also be made "global" by "<<-"
stop("damn, an error occured")

How can I do something like

testthat("double check",
  expect_error_and_TRUE( x == 1, {
                                   x <- 1
                                   stop("damn, an error occured")
                                 }))

I could not find a way to "stack" (pipe) the expect functions?


Solution

  • If a function returns a value it doesn't throws an error and otherwise round. You can test for a specific string in expect_error if you wish, so you could set in the error the value of x.

    {
        x <- 1
        stop("damn, an error occured")
    }
    ## Error: damn, an error occured
    x
    ## [1] 1
    rm(x)
    f <- function(){
        x <- 1
        stop("damn, an error occured")
    }
    f() == 1
    ## Error in f() : damn, an error occured
    expect_error(f(), "damn, an error occured")
    
    f <- function(){
        x <- 1
        stop("damn, an error occured, x is ", x)
    }
    expect_error(f(), "x is 1")
    

    I would advise against testing code outside a function, as it depends on the environment, where it is run, so if you run it in the testing file it might not be the same as in the "main" part of your code