28

I've seen some SO posts explaining how to use pry to step into rspec tests and been able to do this. Once I reach the breakpoint though, I'm struggling to display any useful information. For this code below, I'd like to examine the response object from the pry console:

describe 'happenings' do
  context "#index (GET /api/v1/flat_happenings.json)" do
    before(:each) do
      30.times { FactoryGirl.create(:flat_happening) }
      get "/api/v1/flat_happenings.json"
    end
    describe "should list all flat_happenings" do
      binding.pry
      it { JSON.parse(response.body)["flat_happenings"].length.should eq 30 }
    end
  end
end

Any ideas on how to do this?

James Chevalier
  • 10,604
  • 5
  • 48
  • 74
PropertyWebBuilder
  • 1,286
  • 2
  • 12
  • 18

4 Answers4

42

You should place binding.pry inside it block.

Sergey Alekseev
  • 11,910
  • 11
  • 38
  • 53
25

To use pry in specs we need to add require 'pry' within the spec_helper.rb file. Then we are able to use binding.pry within any of the specs.

iconoclast
  • 21,213
  • 15
  • 102
  • 138
BamBam22
  • 582
  • 10
  • 19
  • 1
    It may not be recommend to add `require 'pry'` to a `spec_helper.rb` file if your project defines `pry` as a development dependency, as opposed to a Runtime dependency. Pry is a development gem that might not be recommend on a release of your library. – ddavison Mar 30 '21 at 22:03
6

This should work:

describe 'happenings' do
  context "#index (GET /api/v1/flat_happenings.json)" do
    before(:each) do
      30.times { FactoryGirl.create(:flat_happening) }
      get "/api/v1/flat_happenings.json"
    end
    it "should list all flat_happenings" do
      binding.pry
      JSON.parse(response.body)["flat_happenings"].length.should eq 30
    end
  end
end

HTH

a.s.t.r.o
  • 3,261
  • 5
  • 34
  • 41
3

I try to require pry when I actually use it, otherwise, it might introduce some unusual bugs (unusual but it can happen) So that means if you only want to debug a particular test, you don't need to require 'pry' in your spec_helper.rb you can use require 'pry' just in the test you want to debug.

def method_i_am_debugging
  puts 'does stuff'
  require 'pry'
  binding.pry
  # ...
end
Sumeet Raina
  • 117
  • 6