What is a bug?
A bug is an error or fault with a program that causes an unexpected or incorrect result. There can be many causes of bugs with some including issues with the code itself e.g typos, syntax errors and undefined variables or issues with unexpected behaviour which means that the code is running fun but the expected result is not being produced - unit tests are good at catching these types of errors e.g the below will show whether your program is producing unexpected results:
fizzbuzz
prints Fizz if the number is 3 (FAILED - 1)
Failures:
1) FizzBuzz prints Fizz if the number is 3
Failure/Error: expect(fizzbuzz(3)).to eq 'Fizz'
expected: "Fizz"
got: 3
1 example, 1 failure
An important point to mention is that no matter your testing methodology, if you come across an error that does not have a test case already written, you should write a test case that reproduces the bug, this will help keep you focused on fixing that bug and highlight if that bug happens again.
What does a good debugging process look like?
1. Tighten the loop
The first step is to find where the error is originating from.
2) RandomHappyEmoji::new returns a :D emoji as a string
Failure/Error: super(HAPPY_EMOJI.sample)
NameError:
uninitialized constant HAPPY_EMOJI
# ./lib/random_happy_emoji.rb:10:in `initialize'
# ./spec/units/random_happy_emoji_spec.rb:11:in `new'
# ./spec/units/random_happy_emoji_spec.rb:11:in `block (3 levels) in <top (required)>'
By reading the stack trace in the error message you can find the file and line number.
# ./lib/random_happy_emoji.rb:10:in `initialize'
The line above highlights file and line the error message is originating from. Error message contains a lot useful information to help point you in the right direction - although arguably some languages are more helpful than others.
2. Get visibility on the error
The next step would be to read the code where the error is located and see whether you can you follow what is happening in your code. Are there any tools that will help you see what your code is outputting at each step?
Ruby has the p command which can be used to return a value on a specific line, variable or method call.
JavaScript has console.log() and the debugger in your chrome dev tools
3. Make a change and run a test
Only make a change to the code when you have a clear idea of what is going on. Check if your test has made a change to the error message - if not you can undo that change.
One thing that I can't stress enough is making sure you read your error messages, on numerous occasions I have sat there scratching my head before noticing that the console is shouting something like 'unexpected token ; on line 5'. If you notice this happening it is probably time for a break.
Top comments (0)