10 Testing Functions

In this chapter, we’ll focus on testing the functions and example data we have incorporated into our package. Ensuring that everything works as expected is a crucial step in package development.

10.1 Loading the Package

Before testing, we need to load our package. We can do this using the devtools::load_all() function, or alternatively, by clicking the “Load All” button in the top-right pane of RStudio.

10.1.1 Using devtools::load_all()

To load your package using devtools::load_all(), simply run the following code in your R console:

devtools::load_all()

10.1.2 Using the Load All Button

Alternatively, you can load your package using the “Load All” button in the top-right pane of RStudio. It can be found in the Build tab. Click the gear-looking “More” icon and select “Load All” to load all the functions and data in your package.


Here’s a visual guide:



10.2 Testing the Functions

Once the package is loaded, we can start testing our functions to ensure they work as expected.

10.2.1 Testing random_movie_recommendation

To test the random_movie_recommendation function, simply call it in the R console:

random_movie_recommendation()

You should see a random movie title from the ggplot2movies dataset. See visual guide below:



10.2.2 Verifying the Example Data

We can also verify that our example data has been correctly incorporated by simply viewing it:

example_data

This should display the dataset we created earlier. See visual guide below:



10.2.3 Testing calculate_group_mean

To test the calculate_group_mean function, call it with the example_data dataset:

calculate_group_mean(example_data, "Age", "Likes_Coffee")

This should return the mean age of the group who likes coffee (denoted by the Likes_Coffee variable). See visual guide below:





In the next section, we will document our functions and example data properly.




Creating R Packages: A Step-by-Step Guide by Ville Langén is licensed under CC BY-SA 4.0