Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging 'testthat' tests in RStudio

Is it possible to invoke the debugger in RStudio when running testthat tests? I haven't been able to find a setup that allows this (various combinations of "use devtools package functions if available" in the settings, hitting the "Test Package" option in the "Build -> More" menu, running test() in the console, putting in browser() calls, etc.) but haven't found a way yet.

I also find myself getting lost a lot when testing, unsure whether the code being run has been installed in the system libraries (by doing 'Build & Reload'), or is being run in situ from the local R directory, or what - sometimes RStudio complains that a breakpoint can't be set until the package is rebuilt (so I suspect the former) or doesn't (so I suspect the latter). Not sure if this issue is closely related or not to my main question.

Without finding a way to drop into the debugger, I end up pasting test code into the console & working in a very ad-hoc fashion, and basically shooting my TDD habits in the foot. So any advice would be appreciated - if it's not possible to invoke the debugger, any suggested workarounds?

I'm running RStudio version 0.99.447 on OS X, in local mode, with R 3.2.1.

Edit - I'd also love to know more background about the options, e.g. "option X will never support debugging, because it's running in a forked process, try this other option Y instead."

Update - having had no responses here, I also asked at https://support.rstudio.com/hc/communities/public/questions/204779797-Debugging-testthat-tests-in-RStudio (where I also haven't had any responses).

like image 816
Ken Williams Avatar asked Jul 21 '15 20:07

Ken Williams


1 Answers

The following works for me:

  1. Insert a call to browser() somewhere within the testthat unit tests.
  2. Run devtools::test() from the RStudio console (instead of using the "Test Package" menu item from the UI)

Then, when the test runner hits the browser() invocation, you should be able to use the environment browser and step through the code.

I haven't found a way to get testthat to stop at breakpoints, but inserting browser() invocations is a pretty close substitute.

To be absolutely sure that you're starting from a consistent state when it comes to loading packages, you can close RStudio, re-open it, run "Clean and rebuild", and then devtools::test()

Lastly, if you're working within an RStudio package, you may want to check out the following advice from RStudio support:

In order to debug effectively in your package, you’ll also want to ensure that your package is compiled with the --with-keep.source option. This option is the default for new packages in RStudio; if you need to set it manually, it can be found in Tools -> Project Options -> Build Tools.

like image 186
alev Avatar answered Oct 15 '22 01:10

alev