Some of the most downloaded R packages are built on Travis CI. In this cookbook, you'll see how easy it just is to setup Travis CI in an existing R project.

# Getting started with R

Let's assume you have a file called `basic_operations.R`

, and it reads something like this:

```
add <- function(a, b){
result <- a + b
return(result)
}
subtract <- function(a, b){
result <- a - b
return(result)
}
divide <- function(numerator, denominator){
if(denominator == 0){
stop("Nah")
}
else {
result <- numerator / denominator
return(result)
}
}
```

## Implementing Travis CI

Now, you want to have automated testing. Thankfully there's Travis CI! Let's start off with the `.travis.yml`

file:

```
language: R
cache: packages
warnings_are_errors: false
```

## Unit Tests

For unit tests, we want to use something called `testthat`

. Let's say we named our whole project `sampleR`

. Your initial `testthat.R`

file would look similar to this:

```
library(testthat)
library(sampleR)
test_check("sampleR")
```

In your `tests`

directory, you'll notice `/tests/testthat`

and let's say you have a file in there entitled `test-basic_operations.R`

, and it goes as follows:

```
test_that("addition works", {
a <- runif(1)
b <- runif(1)
expect_equal(a + b, add(a, b))
a <- -1 * runif(1)
b <- runif(1)
expect_equal(a + b, add(a, b))
})
test_that("subtraction works", {
a <- runif(1)
b <- runif(1)
expect_equal(a - b, subtract(a, b))
a <- -1 * runif(1)
b <- runif(1)
expect_equal(a - b, subtract(a, b))
})
test_that("division errors if zero", {
expect_error(divide(1, 0), "Nah")
})
test_that("division works", {
a <- runif(1)
b <- runif(1)
expect_equal(a / b, divide(a, b))
a <- -1 * runif(1)
b <- runif(1)
expect_equal(a / b, divide(a, b))
})
```

You can see in this unit test, we are testing if `division`

, `addition`

, and `subtraction`

passes the unit test.

## Finishing up

At this point, you're all set, and ready for your `R`

project to build. Last but not least, there are alternative ways to get packages when building out your `.travis.yml`

. For example if I wanted to get packages from GitHub, it would look something like this:

```
r_github_packages: r-lib/testthat
```

The other alternative is to use `CRAN`

. This is how it would look grabbing your package from `CRAN`

:

```
r_packages:
- testthat
```

Slight variants, but just different methods on getting the same package. It just comes down to your own approach and method.

## Oldest comments (2)

I've been following Montana Mendy's posts intensely, simply because he's a friend / trendsetter (friendsetter?) in the programming community.

I will continue reading his articles until Dev.to either bans him like Mission CHeese, or he decides to start a personal blog. But I imagine regardless he's going to be syndicating, so good job on this helpful Stats Article [everyone needs stats]..

Thanks Mendy! Learning with each blogpost and shows high technicality/precision.

Thank you Ben!!