using rlang with testthat (eval(bquote() to rlang)

I'm getting stuck translating the following example of https://r-pkgs.org/tests.html to rlang notation. I'm missing something about how to do something equivalent to eval(bquote

library(lubridate)
as_time <- function(x) as.POSIXct(x, tz = "UTC")
expect_floor_equal <- function(unit, time) {
        eval(bquote(expect_equal(floor_date(base, .(unit)), as_time(.(time)))))
}
base <- as_time("2009-08-03 12:01:59.23")
expect_floor_equal("second", "2009-08-03 12:01:58")

I thought that this would work:

expect_floor_equal <- function(unit, time) {
    unit <- rlang::enquo(unit)
    time <- rlang::enquo(time)
    rlang::eval_bare(expect_equal(floor_date(base, unit), as_time(time)))
}
## Error in unit[[1]] : object of type 'symbol' is not subsettable
## In addition: Warning message:
##                          In parse_period_unit(unit) :
##                                 Unit argument longer than 1. Taking first element.y

How should I do it?

Following this NEWS information
https://testthat.r-lib.org/news/index.html#quasiquotation-support

I would just to it that way using only !!

library(testthat)
library(lubridate)
#> 
#> Attachement du package : 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

as_time <- function(x) as.POSIXct(x, tz = "UTC")
base <- as_time("2009-08-03 12:01:59.23")

expect_floor_equal <- function(unit, time) {
  eval(bquote(expect_equal(floor_date(base, .(unit)), as_time(.(time)))))
}
expect_floor_equal("second", "2009-08-03 12:01:58")
#> Error: floor_date(base, "second") not equal to as_time("2009-08-03 12:01:58").
#> 1/1 mismatches
#> [1] 2009-08-03 12:01:59 - 2009-08-03 12:01:58 == 1 secs

expect_floor_equal <- function(unit, time) {
  expect_equal(floor_date(base, !!unit), as_time(!!time))
}
expect_floor_equal("second", "2009-08-03 12:01:58")
#> Error: floor_date(base, "second") not equal to as_time("2009-08-03 12:01:58").
#> 1/1 mismatches
#> [1] 2009-08-03 12:01:59 - 2009-08-03 12:01:58 == 1 secs

Created on 2019-12-19 by the reprex package (v0.3.0.9001)

Where you looking for another behavior ?

1 Like

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