Cucumber Tip: IRB From Inside a Step Definition

Most Ruby programmers know about Ruby’s interactive console, IRB. (If you don’t, stop right here, open up a command window and run irb. Type some Ruby code. See how it returns the result of each line right away.) IRB is great for poking around with unfamiliar libraries.

Suppose you’re using Capybara with Cucumber for the first time. It would be nice to use IRB to experiment with what Capybara can do on a particular page. You could launch an IRB session and duplicate all the Capybara setup from your Cucumber support/env.rb file. But wouldn’t it be nice if you could just fire up IRB in the context of a step definition so you know everything in your IRB session matches what you’d get in the step def? Turns out you can. Here’s how…

Install the ruby-debug gem. If you’re using Ruby 1.9 like me, you need the ruby-debug19 gem. In Rails 3, just add gem ruby-debug19 to your Gemfile, probably in the test group, and run bundle install.

Require ruby-debug in support/env.rb.

Add breakpoint where you want to jump into IRB. For example:


Given /^I am on the advanced search page$/ do
visit 'http://http://www.google.com/advanced_search'
breakpoint
0
end

(Note the extra line after breakpoint with 0 on it. breakpoint breaks before executing the next line, so if it’s the last thing in a block, you won’t jump into the debugger in the context you expect; 0 is a dummy line to keep us in the right context.)

Run Cucumber like normal. When it reaches breakpoint, ruby-debug will take over, and you’ll see a prompt like this: (rdb:1).

You can do a lot of different things at this prompt, but we only care about one right now: type irb and hit Enter. Now you should see a an IRB prompt. You’re in the context of a Cucumber step definition. Type self and hit Enter. You’ll see that self is an instance of Cucumber’s World with various things mixed in. From here, you can do anything you would do inside that step definition.

When you’re done, run quit to get out of IRB and continue to get out of the debugger. Cucumber execution will continue like normal. Keep in mind, though, that if you change the state of your system from IRB, you might not get the test results you expect.

Enhancements and variations for you to explore:

  • Make IRB nicer to use with gems such as irbtools
  • Create a step definition just for launching the debugger
  • Create a tagged scenario just for launching the debugger

Last updated