Debugging Cucumber Tests With Ruby-Debug
Today I ran into a scenario where I needed to step through some ruby code and examine the state of various objects in my rails app. I’ve used the ruby-debug gem a number of times to do exactly this. However, this scenario was being run via cucumber. After some quick googling, I found a number of blog posts saying that you should be able to stick a ‘debugger’ statement anywhere in your code (including your feature step definitions) and it should work. An hour after I started trying, I finally got it working thanks to Tim Tyrrell.
Getting It To Work
Here’s the first things that I did to get ruby-debug to work with cucumber.
The first chunk of code in my Gemfile ensures that I have the ruby debugger loaded up. I’ve had this line in my Gemfile for some time now, since I’ve done debugging of my rails apps.
The second chunk of code in the cucumber env.rb file is the magic sauce that I needed to get this working. Once I added that line to this file, I was able to place a ‘debugger’ or ‘breakpoint’ statement anywhere I wanted and ruby-debug attached correctly.
The last chunk should go in some cucumber step definition file. It’s a convenience step that Tim also suggested adding. That way, you can just add “Then I debug” as a step to any cucumber feature file, and step into the code at that point. This is useful when you don’t know exactly where the code is failing and you want to attach the debugger prior to the failing step.
Doing It Right With Bundler’s :require Option
I’m a little surprised that I had to add the require ‘ruby-debug’ to my env.rb file, honestly. Bundler usually handles the ‘require’ for you, when you include a gem … except that the gem is named ‘ruby-debug19’ and the require statement is ‘ruby-debug’, which breaks the convention that bundler uses to do the include.
Fortunately, we can fix the Gemfile to specify by specifying the :require option.
Now that I have my Gemfile properly loading ‘ruby-debug’, I can get rid of the require “ruby-debug” line in my env.rb file. Re-run the cucumber suite, and the debugger attaches correctly.