Testing character strings using custom classes.

I've a character vector that uses a custom class foo.

bar <- structure("foo", class = c("foo", "character"))

When comparing this object against the string "foo", the test complains that classes don't match.

test_that("foo", {
  expect_equal(bar, "foo")
})
#> ── Failure (Line 2): foo ───────────────────────────────────────────────────────
#> structure("foo", class = c("foo", "character")) (`actual`) not equal to "foo" (`expected`).
#> 
#> `actual` is an S3 object of class <foo/character>, a character vector
#> `expected` is a character vector ('foo')

I've ended up using the ignore_attr = TRUE parameter in expect_equal() but it's not convenient because I have to use it in many tests (the waldo::compare() doc also recommend not to use it for good reasons).

I've noticed that testing glue strings (classes glue/character) work so there might be a way to make my test work without ignoring attributes.

test_that("foo", {
  expect_equal(glue("foo"), "foo")
})
#> Test passed

How can I make my test pass without ignoring attributes or unclasing the input object?

If you have many tests like this, then I would write a helper function, that

  1. tests the class first,
  2. then drops the class and tests the rest with expect_equal().
1 Like

Ah yes, forgot to mention it but I was thinking about doing that as well.
Just out of curiosity, why does it work with glue()? Is it because the package uses special constructors from the vctrs package?

No, glue does not use vctrs, but it does define an S3 method that testthat 3e (waldo) picks up: Add compare_proxy method and convert to testthat 3e · tidyverse/glue@274130c · GitHub

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.