I'd like to test that one of my functions gives a particular message (or warning, or error).
good <- function() message("Hello")
bad <- function() message("Hello!!!!!")
I'd like the first expectation to succeed and the second to fail.
library(testthat)
expect_message(good(), "Hello", fixed=TRUE)
expect_message(bad(), "Hello", fixed=TRUE)
Unfortunately, both of them pass at the moment.
For clarification: this is meant to be a minimal example, rather than the exact messages I'm testing against. If possible I'd like to avoid adding complexity (and probably errors) to my test scripts by needing to come up with an appropriate regex for every new message I want to test.
Your rexeg matches
"Hello"
in both cases, thus it doesn't return an error. You''ll need to set up word boundaries\\b
from both sides. It would suffice if you wouldn't use punctuations/spaces in here. In order to ditch them too, you'll need to add[^\\s ^\\w]
You can use
^
and$
anchors to indicate that that the string must begin and end with your pattern.The
\\n
is needed to match the new line thatmessage
adds.For warnings it's a little simpler, since there's no newline:
For errors it's a little harder:
Note that any regex metacharacters, i.e.
. \ | ( ) [ { ^ $ * + ?
, will need to be escaped.Alternatively, borrowing from Mr. Flick's answer here, you could convert the message into a string and then use
expect_true
,expect_identical
, etc.