Search code examples
runit-testingtestthat

R testthat: How to ignore classes in expected result (error "Classes differ")


How can I ignore the class attribute in testthat unit tests?

Currently the tests fail because of different classes:

library(testthat)

testthat("drinks taste good", {

  values <- c("COFFEE", "TEA", "SOFT DRINK")

  expected.values <- values

  class(values) <- "myclass"

  expect_equal(values, expected.values, check.attributes = FALSE)
  # Error: `values` not equal to `expected.values`.
  # target is myclass, current is character

  # funny: Try it with switched variables causes a different error message
  expect_equal(expected.values, values, check.attributes = FALSE)
  # Error: `expected.values` not equal to `values`.
  # Classes differ: character vs myclass  
})

Edit 1: expect_equivalent(values, expected.values) doesn't work neither since it ignores the attributes but not the class (via check.attributes = FALSE):

Error: `values` not equivalent to `expected.values`.
target is myclass, current is character

Solution

  • You can't ignore class, so have to deal with that difference in your code. As suggested in the comments, unclass() is sufficient in this case.

    As for toggling attributes, class is checked independent of attributes, so you can't toggle it off with the check.attributes argument.

    Also, the funny behavior when switching the order of the values comes from internal method dispatch: it's using compare.default when the myclass value is first and compare.character when the character vector is first.