Posted over 2 years ago. Visible to the public. Repeats.

Ruby: How to use global variables for a conditional debugger

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

Example:

Copy
class User after_save { byebug if $debug; nil } def lock self.locked = true save end end
Copy
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.

Flaky tests are tests that sometimes fail for no obvious reason. They are the plague of many end-to-end (E2E) test suites that automate the browser through tools like Capybara and Selenium.

Join our free training event and learn to fix any flaky test suite, even in large legacy applications.

Owner of this card:

Avatar
Emanuel De
Last edit:
11 days ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more