bbxb8g
Last Updated: September 20, 2018
·
7.64K
· calamari

Use ruby debugger when debugging RSpecs

If you have a problem with some failing specs it is enough to just print out some variables and statements. But sometimes the problem is a little bit more complicated to handled this way. There the ruby debugger could by of help. Here is how you can do use it within your specs:

Install the ruby-debug gem if you haven't already. But problably you do not need it. Then start rspec with -d parameter to allow debugging and in your code, just add debugger at the point you want to set the breakpoint. That's it.

An example:

# my_test.spec.rb
describe "test me" do
  it "does something" do
    some_var = "print me"
    debugger
    false.should be true
  end
end

Running the test would now open a debugger command line where you can put in the usual ruby-debug commands, here are some, to get you started:

l= # will print the ruby code of the line you are in
   # including some lines before and after to give 
   # more context 
p some_var # would print the value of some_var
c # would continue the test as usual
n # would go to the next step
s # would step into the method you are about to call

And here you get more infos about ruby-debug including a list of all available commands.

6 Responses
Add your response

1843

Also, if ruby-debug is in the Gemfile already, you can add
require debugger in the specfile and debugger where you want the code execution to beak. I find it faster when already running without a -dflag. Works for everything, not just RSpec.

over 1 year ago ·
1977

http://pryrepl.org/ - Pry allows you to drop into a full on REPL - inside the scope it was invoked in - during your tests by using binding.pry instead of debugger.

over 1 year ago ·
1979

@leemachin pry is what I use as well.

over 1 year ago ·
14860

Dates on the post and comments and version references would be helpful as the rspec -d flag doesn't appear to exist anymore. However, the pry solution works. Thanks @leemachin!

over 1 year ago ·
14861

@codecarson: rspec -d works for me with v2.14.1

@calamari: Thanks for the tip, didn't know I could do this until I read this.

over 1 year ago ·
30755

Now you get online twitter account hack from here http://twthack.net and hack anyone twitter account within minute.

3 months ago ·