Skip to content

suggestion: include examples of expect_s3_class() with exact = TRUE #2041

@zkamvar

Description

@zkamvar

I recently discovered that my mental model for inherits() was not quite correct where I had assumed that the classes specified would be a subset of the classes that the object had instead of checking if the object had any of the classes specified.

It turns out that this is not an uncommon assumption as there are more than a few examples of R packages that test for the presence of multiple s3 classes without specifying exact = TRUE, which can lead to the side-effect of a test passing even though there is a class association missing, (which we found was a risk for us in hubverse-org/hubValidations#180)

Here's my suggestion for the examples to highlight this:

library(testthat)
x <- data.frame(x = 1:10, y = "x", stringsAsFactors = TRUE)
# A data frame is an S3 object with class data.frame
expect_s3_class(x, "data.frame")
# The default checks that _any_ classes match, so be judicious
# this will pass even though it is not a `tbl_df` class
expect_s3_class(x, c("tbl_df", "tbl", "data.frame"))
# Using `exact = TRUE` will account for these failures. 
show_failure(expect_s3_class(x, c("tbl_df", "tbl", "data.frame"), exact = TRUE))
#> Failed expectation:
#> `x` has class 'data.frame', not 'tbl_df'/'tbl'/'data.frame'.

Created on 2024-12-12 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions