Read more

Ruby: How to use global variables for a conditional debugger

Emanuel
July 30, 2019Software engineer at makandra GmbH

You can share a state in Ruby with global variables Show archive.org snapshot . Even if you should avoid them whenever possible, for debugging an application this could be temporary quite handy.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Example:

class User

  after_save { byebug if $debug; nil }

  def lock
   self.locked = true
   save
  end

end
Rspec.describe User do

  let(:user) { create(:user) } 

  before do
   # Many users are created and saved in this hook, but we don't want the debugger to stop for them
   10.times { create(:user) }
  end

  it do
    # At this point we want to stop in the debugger for all following tests, when the :lock call runs into the after_save
    $debug = true
    expect { user.lock }.to change(user, :locked).from(false).to(true) 
  end

end

Running this spec will only trigger one debug session. Otherwise you will have to count how many times you exited the debug session to ensure you are in the "desired" session.

Posted by Emanuel to makandra dev (2019-07-30 12:08)