4

I have a function in a package I'm building that assigns a hex-code to the global environment for use by analysts...

optiplum<-function(){
  assign(
    x="optiplum",
    value=rgb(red=129,green=61,blue=114, maxColorValue = 255),
    envir=.GlobalEnv)
  }

My unit test code is:

test_that("optiplum - produces the correct hex code",{
 optiplum()
  expect_true(identical(optiplum,"#813D72"))
})

When I run the code manually, there isn't an error:

> str(optiplum)
 chr "#813D72"
> str("#813D72")
 chr "#813D72"
> identical("#813D72",optiplum)
[1] TRUE
> expect_true(identical(optiplum,"#813D72"))

When I run a test_file() is also does not error

> test_file("./tests/testthat/test-optiplum.R")
optiplum : .

However, when I run the test as part of my devtools workflow:

> test()
Testing optINTERNAL
Loading optINTERNAL
optiplum : 1


1. Failure: optiplum - produces the correct hex code --------------------------------------------------------------------------------------------------------------
identical(optiplum, "#813D72") isn't true

Anyone have any ideas on why this might be occurring and how I can resolve the situation?

Steph Locke
  • 5,951
  • 4
  • 39
  • 77
  • 1
    `test()` does it's best to isolate your tests from the global environment. What you're doing is usually a bad idea. Why not just have `optiplum <- function() "#813D72"`? – hadley Feb 10 '14 at 13:04
  • Primarily I was (perhaps unfounded) working under the assumption that a variable would be quicker than a function when called many times, but the difference is probably so miniscule I needn't worry. Will do as you suggest @Hadley, and change the function. If you post as an answer I'll mark it as such. Cheers – Steph Locke Feb 10 '14 at 13:20

1 Answers1

1

Assignment to the global environment is a no-no, see R Inferno and testthat isolates tests as much as possible (see test_that() details). As a consequence, the optiplum() assignment to the global environment would not succeed because the testthat function strictly prohibits such behaviour.

@Hadley rightly points out that the function should just return the string instead of assigning it, particularly since it is just two extra characters for each use.

So not

optiplum<-function(){
  assign(
    x="optiplum",
    value=rgb(red=129,green=61,blue=114, maxColorValue = 255),
    envir=.GlobalEnv)
  }

but

optiplum <- function() rgb(red=102,green=17,blue=109, maxColorValue = 255)
Steph Locke
  • 5,951
  • 4
  • 39
  • 77