4 tips on debugging rspec unit tests
The past few days I've been teaching myself Ruby on Rails and found myself debugging some rspec unit tests pretty extensively. Here are some things I learned that will help you debug like a pro!
1) Format Your RSpec Test Results
If this is your first time running rspec, the first thing you'll probably do is run rake spec. This runs the tests but formatting will be cumbersome. Best way to format this so it's easy on the eyes is to type this in the terminal:
echo '--format documentation' >> .rspec
So your test results will look wonderfully like this:
2) Use pry To Set Breakpoints
The next thing you should do is download the wildly popular gem pry here.
What is pry? pry is an amazing library that allows you to debug in real-time. So, for example, let's say you want to find the value of x in your application, as part of the debugging process.
To do this, simply type require 'pry'; binding.pry right before x so when you run the unit tests, testing will stop right before the x. Then, while you have frozen the testing process, you can simply type x in the command line to get the value of x.
In a nutshell, use require 'pry'; binding.pry to set breakpoints in your code to examine state in real-time.
Another thing to keep in mind is, usually each unit test (denoted by it) may have several test data that it runs. Therefore, when you use pry to get the value of x, the value of x may be different for each set of test data that is being used.
To navigate each set of test data, just hit Ctrl + D. Then make sure you bundle exec rspec spec/models/message_controller_spec.rspec to run the tests.
3) Print Out Everything!
Let's say you want to check if a function is being invoked. An alternative to using pry is to simply print out a statement to the console, to check if it is even going inside that particular function: p @message to print out the state of @message while unit test is running
4) Isolate Your Tests
When I need to make a bunch of unit tests pass, my technique of choice is to go one-by-one. That way, I am isolate each individual test and my console is much cleaner to look at - instead of looking at the results of 10 different unit tests, I am only looking at 1. To do this, simply type an x in front of each test, or, group of tests:
xcontent "with email params" do
or,
xit {should be_truthy}
Another way to isolate your tests is specify this on the command line. For example, to test a specific unit test on let's say, line 30, you can type the following (note the :30 at the end):
rake rspec spec/models/message_creator_spc.rb:30