Using testthat to test your functions

One of the advantages of divvying up your entire manuscript into functions, is that you can test that they perform properly.

To do so, we are going to use the package testthat that has been designed to test functions written for packages, but it can be applied to any kind of functions.

Make sure you have testthat installed:

install.packages("testthat")

Write a test

Let's start by writing a first test:

## Example of using testthat to check that a function generating a dataset works as expected.
test_that("my first test: correct number of countries",
          expect_equal(length(unique(gather_gdp_data()$country)),
                       length(list.files(path = "data-raw/", pattern="gdp-percapita\\.csv$")))
          )

Syntax

The tests should be wrapped within the test_that function, you then provide a short sentence that explains the nature of the test. Keep it short and meaningful because it will be shown to you if the test fails, and having a clear message will help you figure out the problem.

Tip: Spending a little bit of time thinking about the message helps refine the nature of the test and be more careful about what you test.

Other testing functions

You can use one of the several functions that testthat provides that tells you what you should expect from your function. The most commonly used ones are

  • expect_equal() and expect_true()
  • expect_warning() and expect_error() are useful to make sure that your functions produce warnings and errors correctly

Your turn

Write a test for the get_mean_lifeExp() data, or write additional tests for the gather_gdp_data().

Using Travis CI

Instructor notes

There is not enough time to cover in details how Travis works and use it with the manuscript here. However, I have the manuscript in a different repository https://github.com/fmichonneau/teaching-automation with Travis enabled. I typically demonstrate what it looks like, change something in the data that breaks one of the test and go back a few minutes later to show how the badge changed colors.