Even the most experienced developer will sometimes encounter abnormal behavior from what they believe to be perfectly valid code. script/console is fantastic and extremely helpful for some of those situations, but there are times when it's not enough. You may need more context in order to discover the source of your problem, and that's where ruby-debug comes in.
Getting Ready to Debug
In order to debug your Rails application the first thing you need to do is to install the ruby-debug gem.
sudo gem install ruby-debug -y
Next, you need to set a breakpoint in your application by dropping this cleverly named nugget debugger into your code where you would like to begin the analysis of your app. For simplicity's sake I will just put the debugger in the show action of my PropertiesController.
# GET /properties/1
# GET /properties/1.xml
def show
debugger
@property = @manager.properties.find(params[:id], :include => [:municipality, {:assemblies => :assembly_checks}])
...
end
And now the only thing left is to just start the server with debugging enabled.
script/server --debugger
Easy Peazy.
In order for that breakpoint to actually break though, the debugger statement needs to be evaluated. We can accomplish this by navigating our browser to the show action where the debugger is set. You will notice that once we do this our browser becomes unresponsive. This is because the debugger halts the execution of our application at the breakpoint until we tell it to proceed. So while we are waiting on our browser, why don't we take a look at the terminal.
/Users/joshua/Sites/backflow_testing_app/app/controllers/properties_controller.rb:19
@property = @manager.properties.find(params[:id], :include => [:municipality, {:assemblies => :assembly_checks}])
(rdb:2)
That's kind of cool, we have a nice prompt there just waiting for us to use.
Getting a Lay of the Land
By typing l (or list) at the prompt we can take a look at the first ten lines of code surrounding our debugger statement. Each successive l command will display the next ten lines of code in the current file.
(rdb:2) l
[14, 23] in /Users/joshua/Sites/backflow_testing_app/app/controllers/properties_controller.rb
14
15 # GET /properties/1
16 # GET /properties/1.xml
17 def show
18 debugger
=> 19 @property = @manager.properties.find(params[:id], :include => [:municipality, {:assemblies => :assembly_checks}])
20 @testers = User.find(:all, :conditions => ["is_tester = ?", true])
21 @next_test_date = @property.assemblies.first.next_test_date if @property.assemblies.first
22
23 @next_test_date =
(rdb:2) l
[24, 33] in /Users/joshua/Sites/backflow_testing_app/app/controllers/properties_controller.rb
24 respond_to do |format|
25 format.html # show.html.erb
26 format.xml { render :xml => @property }
27 end
28 end
29
30 # GET /properties/new
31 # GET /properties/new.xml
32 def new
33 @property = Property.new
(rdb:2)
l - will move us back up 10 lines in the file and l = will always return us to the current line or the line to be evaluated next. The current line is designated by the =>. If we want to have a larger context to look at we can specify a range of line numbers and pass that to l, like so l 1-40. If you happen to be using Textmate we can even type tmate and view the entire file in all its colorful glory.
So now that we know where we are in terms of where we are in the file, let's get a sense of where we are from a different perspective. Let's see where we are in terms of the stack trace. We can view the stack trace by typing either backtrace or where. This prints the entire stack trace to the screen with each stack frame numbered from the current frame (0) upwards. We can navigate through the stack by either explicitly selecting the frame to jump to (e.g. frame 20) or by moving a relative number of frames up or down from our current frame. For example, if we are inspecting frame 5, up 5 or down 2 will move us to frames 10 and 3 respectively. The =>, as before, will show us our current location.
Step Into, Step Over and Continue
Let's make some progress and move forward through some of our code. Let's first make certain we are on the current frame by typing frame 0. We can step through our code by using one of two methods - either n (next) or s (step). n is the traditional step over and s is the traditional step into - if we want to dive into the guts of our methods. If we want to move more quickly through our code, perhaps to the next breakpoint, we can use the c (continue) command.
So let's give it a try. Let's just move to the next line of code using n and inspect the @propertyobject using the p command to print to screen.
[14, 23] in /Users/joshua/Sites/backflow_testing_app/app/controllers/properties_controller.rb
14
15 # GET /properties/1
16 # GET /properties/1.xml
17 def show
18 debugger
=> 19 @property = @manager.properties.find(params[:id], :include => [:municipality, {:assemblies => :assembly_checks}])
20 @testers = User.find(:all, :conditions => ["is_tester = ?", true])
21 @next_test_date = @property.assemblies.first.next_test_date if @property.assemblies.first
22
23 @next_test_date =
(rdb:2) n
/Users/joshua/Sites/backflow_testing_app/app/controllers/properties_controller.rb:20
@testers = User.find(:all, :conditions => ["is_tester = ?", true])
(rdb:2) p @property
#<Property id: 690789713, manager_id: 476927875, integer: nil, name: "Borders Books", string: nil, store: "0020", contact: "jon", street_address: "1500 West 16thStreet", city: "Oak Brook", state: "IL", zip_code: "60523", phone: "(630)574-0800", fax: "", email: "someone@borders.com", municipality_id: 1847418, previous_manager: nil, notes: "", text: nil, property_deleted: false, boolean: nil, lat: #<BigDecimal:189a430,'0.41853303E2',12(16)>, decimal: nil, lng: #<BigDecimal:189a0ac,'-0.87997248E2',12(16)>, created_at: "2008-06-14 17:50:39", updated_at: "2008-06-14 18:25:36">
One interesting and occasionally helpful thing to note is that we can make assignments while debugging.
(rdb:2) @property.name = "Josh\'s Books" "Josh's Books" (rdb:2)
Setting Breaks while Debugging
We are not limited to the breakpoints we put in our code (i.e. debugger). We can also set conditional or unconditional breakpoints from within the debugger. The b (break) command takes either a file and a line number or a class and a method as arguments. So if we wanted to add a breakpoint on the edit and delete actions of the PropertiesController for instance we could simply enter this.
(rdb:716) break PropertiesController.edit Breakpoint 1 at PropertiesController::edit (rdb:716) break PropertiesController.delete Breakpoint 2 at PropertiesController::delete
And to delete the edit breakpoint simply specify the number and delete it like so.
(rdb:1132) delete 1
Now let's list our single remaining breakpoint with info breakpoints.
(rdb:1132) info breakpoints Num Enb What 2 y at PropertiesController:delete
irb
The debugger offers us a lot but lacks some of the functionality of script/console or irb. It turns out, however, that that's not really a problem, we can get the functionality of irbeasily enough. By simply typing irb at the debugger prompt we can open an irb session. In this session we have the bindings environment set to the current debugging state of your app and are able to alter the behavior of the application. Once we have done whatever we need in irb we can simply type quit and we will be returned to the same line in the debugger as when we entered irb.
Don't Forget the Help
This is by no means an exhaustive examination of the debugger but rather is a brief introduction to the uninitiated. Don't forget to use h (help) and h command for more information. I also would recommend trying out the cheat gem for a quick reference of this and other helpful cheat sheets.
sudo gem install cheat cheat rdebug
Additional Resources
Lately I've been looking at data. Not always so much data in itself but how data is presented. We are presented with far more information on a daily basis than we can possibly store or comfortably process. Much of it gets overlooked or tossed aside. There is no place where this is more prominent than on the Web. I can't think of how many times I've dismissed a site during a search simply because it was too much trouble find what I was looking for. We don't have time to sift through overbearing gridlines, confusing navigation, lack of whitespace and pages of thousands of links, images and special offers, each of which appear to be the most important thing on the page.
In Envisioning Information Edward Tufte spends a considerable amount of time discussing ways in which various charts, graphs, maps, timetables and illustrations have made attempts at "escaping flatland" &emdash; representing the complex data of our four-dimentional world on a two-dimentional surface. The more effective examples tell their story in an intuitive and sometimes profound way. They not only make the mundane beautiful, they make complex data sets easier to understand.
Consider the Tag Cloud
Actually, I'd prefer that people would forget tag clouds. I'm tired of tag clouds. Granted, a tag cloud is intended to digest data into a more immediately understandable form, but in most cases it comes out as the sort of thing that makes typographers cry (fig 1). They take a potentially useful tool for navigation and searching, and mangle it into a bowl of alphabet soup through which you must sift in order find what you are really looking for.

fig. 1
Here's an exercise in which alternative ways of looking at tags are considered. Maybe it will inspire something better than tag clouds. The data is a list of tags for an archive of fictional articles.
First I'd like to point out that this is primarily an exercise. I'm going to be examining details about a set of data that visitors to a Web site may or may not have interest in. The point is to illustrate how representation of data can highlight different characteristics of that data, and to strive for immediacy of understanding of the data.
Good Digestion
It does seem to be important to many site designers to convey how many things have been tagged by a given tag, and how each tag's frequency relates to that of others. Lets back up a bit and start with the common default way to do this which is to attach numbers to the list of tags (fig. 2). In this example tags are listed in the order they were created.

fig. 2
This is a bit more precise information than a tag cloud presents but it isn't as immediate. There is no apparent order. It is clear that there are more things tagged with Firefox than with Mongrel but you have to work a little (yes, very little) to get that information. It takes a bit longer to figure out which is the greatest and which is the least. Consider how long it would take to figure out which tag is closest to the average.
No, you aren't likely to need to know which tag is closest to the average, but this illustrates the point that the information is not readily consumed. It is like a raw slab of meat. If you ate it now it wouldn't taste very good and it could make you very sick.
Order out of Chaos
The fact that these tags are listed in the order they were created is lost on us. We have no way of knowing that. That may not be the most useful piece of information so lets set it aside for a while and highlight something else.

fig. 3
Here the tags adhere to a clear hierarchy but it still takes a moment to digest. Consider how long it takes to figure out which pair of adjacent tags has the greatest disparity in frequency between them.
Go Long
The problem with numbers is that they are abstract. It is easy to picture 5 apples (I see 5 apples arranged like the dots on six-sided die), but it is more difficult to picture 29 apples. It is less concrete. This is where what Tufte refers to as "small multiples" comes in handy. (1)

fig. 4
Instead of displaying numbers we're now showing actual taggings. Each dot represents a tag on an article. Small multiples provide a reading of the data on a small scale (one dot to the next), and come together as a whole to tell a story on a larger scale.
The list is beginning to behave like a bar graph, showing relative frequency from one tag to the next, but it is better than that. A bar graph can show relationships in value between multiple things, but without numbers those relationships are vague. Their scale is relative. Here the relationships are more explicit, and you don't have to read anything or do any math. Cognition is immediate. While it would be tedious to count each dot in order to know the exact number of something, you do get a general sense of what's going on.
Keep Going
The dots have freed us to make another improvement. This list isn't very long, but it could be. Searching for a specific topic in that list could become tedious if it is not alphabetized. We will make that change and a few others.
Each article can have multiple tags. So clicking on Firefox will bring up a list if articles, some which may be tagged with other things. It would be nice to show that relationship. Our next iteration (fig.5) highlights all relevant taggings. It would also be nice to see which tag is currently selected. This one is interactive.
fig. 5 (interactive)
Clicking on Firefox causes all dots on its bar to turn orange as well as any dots (taggings) that are associated with articles that have been tagged with Firefox. This tells us (very quickly) that of the articles tagged with Firefox, three are also tagged with Thunderbird., none are tagged with Python or Leopard, etc.
The animation is arguably a bit redundant, but I like the way it looks.
Keep Going!
Have we not learned all there is to learn about these humble tags? Never! These tags still have dark little secrets yet to be gleaned. We are working with two (physical) dimensions but we can impose another on flatland-time.
fig. 6 (interactive)
If we stretch data out along a timeline we can learn more about it. I've added some subtle striping and elongated the dots to emphasize concurrent taggings. We can see that early on in the life of this site Duck Typing was a hot topic but its popularity gradually dwindled, Thunderbird had a short but decent run some time ago, and Python has been making itself known of late for some mysterious reason. Our mundane navigation buttons are starting to take on a life of their own.
All anthropomorphism aside, this arrangement is giving us a lot of information very quickly, and without any numbers. But it comes at a cost. At this point we've nearly tripled the area these tags take up, turning turning our lowly navigation into an ever increasingly space hungry monster. We've also understated the frequency relationship between tags a bit. Perhaps we've gone too far but the exercise is not in vain.
Do Good to Data. Do it Well.
In clarifying data, the goal is not simply to simplify. There is only so much fat that can be cut before data becomes further obfuscated. Sometimes, to tell the story well, we need to reveal more information, but it should be done in a way that does not complicate the reading. It should make clear what was once vague.
Further Reading
I highly recommend the following resources for a more detailed discussion on information design.
- Ben Fry
- Edward Tufte
- Accessible Data Visualization with Web Standards, A List Apart
- Bret Victor, Magic Ink: Information Software and the Graphical Interface
Footnotes
- Arguably these are not small multiples as Edward Tufte describes them because these boxes are all the same, but I contend that each box is unique compared to its neighbors because they each represent a unique relationship to an article.
Testing with Selenium
Anyone who has worked on Javascript eccentric web applications knows how much of a hassle it can be. Either you're stuck manually testing endless possible combinations of actions, or you're writing them for your Selenium plugin. Things get even worse when your client wants to support browsers like IE6. RSpec has encapsulated the behavior driven development of models, controllers and views, and user stories have integrated testing between the layers, but unfortunately neither has done much in the development of interactive web applications.
Working on Javascript applications after learning RSpec can be a painful experience. Your fingers want to write simple tests, whereas Javascript wants to you painfully point and click until everything works together. For years I have been nagging myself to find a headless browser that could be integrated into my development environment, but I simply never had the time, energy or justification to take action. Tired of pointing and clicking repeatedly after every change, I recently became filled with angst and decided it was time to do something about it.
I was first exposed to Selenium a few semesters back, and while I was unimpressed with the end product, it was the first and only project of its kind I was aware of. My first impression of Selenium was based on personal preferences and not scientific merits, so I thought a second impression was due. To my dismay, Selenium still has an interface that appears to have been designed only for Windows, and still exists as a glorified macro editor. While Selenium continues to be a bust, I did come across SeleniumRC which is built to test multiple browsers on multiple platforms.
A Better Selenium?
SeleniumRC exists as a server that acts as a proxy between a HTTP client and a browser. Clients send commands to the SeleniumRC server, which passes those actions on to the SeleniumCore inside of the browser window with the matching session id. SeleniumRC returns each request with the result of the command, allowing the client to control and test pages just as a user would. Therefore SeleniumRC can be scripted using any language that can send an HTTP request, like Ruby, JRuby, or Intel Assembly.
Immediately seeing the possibilities, I set out to plug the SeleniumRC Ruby client into RSpec, which would allow me to write user interaction specs in Ruby. While plugging the SeleniumRC client into RSpec proved to be almost as easy as drag and drop, the honeymoon quickly faded. Getting the tests to run and pass turned into a seemingly endless adventure, where sometimes XPaths wouldn't work, sometimes browsers wouldn't work... a big mess. A good portion of my time was spent testing if my behavior tests would work rather then writing the tests and functional code.
I tried two different approaches in overcoming the issues with XPath that I experienced. The first involved passing Prototype strings to be evaluated to avoid SeleniumCore all together. Unfortunately, for some reason I was unable to discover, none of the Prototype strings were returning values. The second approach used Hpricot to assert the presence of elements or values, as well as generating the XPaths for those elements, which could then be passed to SeleniumCore. Alas, XPath selectors were still not working when they were generated by Hpricot.
In addition to having difficulties in getting the tests to work, the syntax provided by the Ruby client is not very pleasing to the Rubyist's eye. I never expect a 'bonus' piece of code, packaged with a free product still in beta, to be the cat's meow. Still, it is always nice when the syntax is clean and all of the pieces work correctly. Does Ruby written to test Javascript have to look like Javascript?
Another issue I've found with SeleniumRC is that it is as slow as my grandma driving a Cadillac down the expressway on Sunday. Even when running the server and client from your local machine, the tests take an extraordinary amount of time to run. I believe this is due to the manner in which SeleniumRC makes it all possible, and while it may be tolerable when doing full scale testing, it simply is not when practicing BDD.
SeleniumRC is still a beta product, listed as version 1.0 beta. While I agree with the term beta, I feel that in today's day and age software should be roughly usable at version 0.1. Typically I would have no problem working around these issues for something I really want; however active development turns into more of a requirement then a wish. There have only been two releases of SeleniumRC since 2006, with the most work being done in the first half of 2006.
A New Hope
Although SeleniumRC hacked my enthusiasm into pieces, it did manage to further motivate my quest for a headless browser. Taking the ideas I got from my time spent with SeleniumRC and RSpec, I set out to create a class that would allow me to control a virtual browser instance from a Ruby object. I decided to look back at my ObjectiveC/Cocoa experience and poke at the WebKit API for a bit and see what sort of trouble I could get myself into.
With a little bit of elbow grease and Google, I have been able to get a working instance of a WebKit browser neatly bundled as a Ruby object. Currently Javascript strings can be passed to the browser to be evaluated, with their string result being returned.
While there are a few technical details to be worked out, with any luck the power of WebKit in Ruby combined with the magic of RSpec should free the masses from the infinite loop of edit-reload-edit. Of course visual aspects will still need manual testing, as well as user interaction on other browsers. With a little finesse, the same tests written to be tested locally with WebKit could also be used to test remote browsers using SeleniumRC.
Next time I hope to have a working demonstration and sample code, in the meantime here is some eye candy you can feast on!




