Debugging Capybara Specs
I recently upgraded Mindful Choices from Rails 4.2 to Rails 4.3
Inevitably, a few of my previously passing specs started to fail after the minor version bump. Here’s an example:
Despite the complex description, the failing spec actually tests some very simple behaviour. Based on the value of a radio-button, an appropriate input element (file upload or text box) should be displayed to the user.
The code was clearly working correctly if I tested it locally using FireFox, so why the failing test? As always, Google yielded several tips for debugging Capybara specs, my favourites are listed below.
Capybara Screenshot:
I had a hunch that perhaps the Rails Asset Pipeline wasn’t working correctly in the test environment. Could my spec be seeing an unstyled, unscripted DOM? Let’s take a screenshot at runtime and see how things look.
Aside from some broken fonts (urgh), everything looks OK, the stylesheets are certainly being applied! Perhaps it’s not an asset pipeline issue, after all.
Good old console.log
My next theory was that, for some internal reason, the javascript might not be executing within the Capybara browser. How can you tell whether JavaScript has executed on a page? Print a message to the console, of course:
Use byebug to pause execution of your spec and the webkit capybara driver to grab any messages from the console:
Check Your Assertions
After eliminating the asset pipeline and JS environment from my investigation, I turned my attention to the spec itself.
This is the assertion that I wrote many months ago, and that up until now has been passing reliably:
Believe it or not, refactoring the spec to this alternative form made it pass first time!
I guess that’s Occam’s razor in action.