Getting Started with Rails Testing

I gave a presentation at the January 2013 Boston Ruby Project Night on “Getting Started with Rails Testing”.

This talk aims at understanding the development workflow while using TDD and the Red-Green-Refactor loop.

We look at the different test types that you can write in a Rails application

  • Unit tests
  • Controller tests
  • Integration tests

We also look at some of the tools and frameworks that are available for testing, including RSpec, MiniTest, Test-Unit, Capybara, and FactoryGirl.

A simple example is used to show the test-driven development workflow.  The code for the example is on github at https://github.com/mdenomy/expense_tracker.

The github repository uses branches to capture a series of snaphots in the test-driven-development workflow.  See the Readme file for a list of the branches, or run the “git branch -a” command to see the full list from the terminal.

Intermediate JavaScript

I recently gave a brown-bag talk on advancing your Javascript skills from the beginner to intermediate level, covering the following topics.

  • Variable scoping rules
  • Object oriented programming
  • Prototype-based inheritance
  • Anonymous functions
  • Module pattern

The code and tests for the presentation can be found here.

I highly recommend following up with the references that I used for preparing the talk for a more in-depth treatment of each of the topics.

An Active Listening Retrospective

The team I am on holds a retrospective at the end of each week-long iteration.  I am a huge fan of retrospectives as they can help teams improve their processes and nip developing problems in the bud.

Our team has a lot of Agile experience and we typically trade off the facilitator role, so the retrospectives have a nice variety of styles and everyone gets a chance to improve their facilitating skills. Our retrospectives normally gravitate towards process improvements or specific technologies that we can improve as a group.  This week however, I wanted to experiment with a new format that I came up with influenced by some meditation and mindfulness practices that I have learned over the years.  One of the techniques I wanted to use in the retrospective was active-listening.

Some of the questions that were on my mind…

  • When we are pair-programming and our pair asks a question are we giving our full attention to what they are asking, or are we more focused on the problem that we are working on?
  • When someone raises an issue at the team standup, are we mentally preparing our rebuttal and not focusing on what is being said?

Laying the Groundwork

This style of retrospective needs to be held in a quiet place like a conference room, with enough room for team members to spread out in pairs without distracting one another.

At the start of the retrospective I reminded the team that we had all probably come from working on some challenging task, and our minds may still on those tasks to some extent.  To be fully present at the retrospective, I asked everyone to take a moment to clear their minds and focus on being present.  Next time I may try a short breathing exercise to help that process, but sometimes just reminding people to be present is enough for them to realize the distractions that may be going on for them and to put them aside.

The Mechanics

I asked everyone to take a few minutes, in silence, to think about what happened in the last retrospective.  What went well, what could have been improved, what pleased them, what frustrated or challenged them, whatever came to mind from the iteration.

I then asked people to pair up.  I chose names out of a hat because I wanted the pairs to be random and possibly have people pair up with someone that they might not normally seek out.  Also it eliminates the stress of “choosing” someone.  If there is an even number of people at the retrospective, the facilitator can participate, otherwise they focus solely on facilitating.

I then instructed the pairs to find some space away from the others, and for a few minutes (3 minutes in our case) one of the people would be the speaker and the other would be the listener.  I encouraged the listener to pay close attention to what the speaker was saying, and try not to form responses in their minds.  If the conversation lagged the listener could ask open-ended questions, but ideally they would focus only on listening to what the person was saying.

After the 3 minutes was up, I asked each of the listeners to tell the group what they heard from their speaker.  Everyone did a great job recalling what was said.  After each “listener” spoke I asked the “speaker” if the listener accurately relayed their conversation and if anything had been left out, which gave them a chance to fill in the gaps or clarify something that was said.

We then repeated the process changing speaker and listener roles.

After everyone had a chance at the “speaker” and “listener” roles.  I went around the room and asked each person if they heard anything that stood out in particular or that surprised them.  I made a conscious effort to allow each person to say what was on their mind, without getting a conversation started with the whole group.  If others chimed in I asked them to please wait until everyone had a chance to speak before we turned it into an open discussion.

A few common themes emerged from the individual observations, and after everyone had a chance to speak individually we discussed the common issues for a bit and came up with some actions to address them coming out of the meeting.  I wrapped up the meeting reminding everyone that we are often hyper-focused on the problems in front of us and may not give one another our full attention, but that we should be mindful of that and try our best to listen to one another.  I hope we can build on that as a team.

The Take-Away

One of the coolest things about the format, that I didn’t realize until it was happening, was that everyone got a voice through someone else telling their story about the iteration.  It is inevitable on any team that some people are more outspoken than others (I am no shrinking violet), but this way everyone got the floor.

I think it was also an opportunity to remind everyone that we each have our own perspectives and we should respect and try to understand each other, even when we may not agree.

Total time for the retrospective, with 6 participants, was 45 minutes.

Further Reading/Watching

If you are new to retrospectives, I highly recommend Esther Derby and Diane Larsen‘s book Agile Retrospectives – Making Good Teams Great.  It has great techniques for organizing and facilitating retrospectives so that they are most effective.  They also have formats that are designed to address specific issues that may be a concern for your team.

If you are interested in mindfulness, I recommend that you check out the Center for Mindfulness at the UMass Medical School or take a look at these videos with Jon Kabat-Zinn, founder of the Center for Mindfulness, speaking at Google.

Craftsmanship and When Not To Refactor

I love learning how to write better software.  That was the attraction for me to the Software Craftsmanship movement.  Here is a group of folks that are concerned about developing  software in a way that is extensible, testable, and maintainable.  I have learned so much about techniques like SOLID, different pair-programming strategies, TDD, DRY, and the list goes on and on and on.

But let’s not lose sight of our jobs here.  We are paid to develop features that our customers need.  Our customers are not going to care how the software is crafted under the covers, unless it gets in the way of us being able to add new features, extend existing ones, or provide a reliable platform.

We have an awesome team room where I am working, with all kinds of information radiators that help us do our jobs and communicate to our customers how we are doing.  We keep our retrospective goals on 3×5 cards in a visible place so they stay fresh in our minds.  Lately, as a result of some pain we felt adding new features, we have been pushing hard to refactor code that gets in our way or makes it difficult to extend the software.

Here are what two of the cards remind us about our refactoring practices:

Refactor all the time as you go.

This encourages us to keep the code clean while we are developing in, remembering the “refactor” in the “red-green-refactor” loop and avoiding the “red-green-red-green-red-green-refactor-refactor-refactor-refactor-refactor-refactor” anti-practice.

If any code is slowing you down, change it (in small slices)

This drives us to fix code that is making it difficult to maintain or extend the code.

There is no card though that says “If you see something you don’t like, change it”, and I think this is where you can get in trouble with the notion of “merciless refactoring“.

We’ve all written code we don’t like or would write differently knowing what we know now as opposed to last year, last month, or even last week.  But that is not carte blanche to re-write something just because it comes into our eye-line.  If it gets in our way, that’s a different story, but we need to keep our eyes on the prize and that prize is the new feature that we promised our customer at the end of the iteration.

Anyway, that’s my two cents.  This soap-box I am standing on is starting to creak, so I better get down now.  Please feel free to share your thoughts or observations.

P.S. In thinking about this I saw some good posts on the subject that you may find interesting:

http://devblog.avdi.org/2012/06/25/every-day-in-every-way/

http://dannorth.net/2011/01/11/programming-is-not-a-craft/

Stone Soup Development

I consider myself lucky to work in an environment that not only follows, but embraces, Agile and XP practices.  We follow test-driven development.  We pair program almost all the time, and we switch pairs frequently, usually at least once per day.  The benefits of these practices hit home this week during our iteration retrospective when the question was posed “What were you proud of this week”.

There were some interesting problems with very creative solutions that happened during the iteration, but the thing I was most proud of was a simple little piece of code.

Around the middle of the iteration I worked on a “calculator” that made some determination based on a set of rules.  We’ve all written code like this 1000 times before, it was not an especially difficult task.  But it was the kind of thing that could get ugly pretty quickly, and yet still “work”.  It was the kind of algorithm that could have easily morphed into a nasty tangle of boolean logic.

Instead, my pair and I started out with a few simple cases and applied a few brute force implementations in the “Calculate” method.  We continuously refactored as more tests were added and the complexity grew, reducing duplication and breaking the problem up into more digestible chunks.  At some point, my original pair swapped out and someone else swapped in for an hour.  It was late Friday, we improved some of the naming, added a few more test cases and supporting logic, then called it a day.  Energized work in action.

Monday morning, a new person swapped in.  Normally I would have swapped out since I had been on it the longest, but there were a few scheduling conflicts and so I stayed on.  We finished the class, ending up with very expressive names, a “Calculate” method that read like plain English, and small methods that did one thing, and did them right.  Again, this problem wasn’t rocket science, but it was done right.

Everyone brought something to the problem and helped refine the design.  We discussed trade-offs, avoiding traps like “my idea” and “your idea”.  After discussing it at the retrospective, it reminded me of a story that I learned as a kid called Stone Soup.  We started with nothing, everyone threw a little something in the pot, and we came out in the end with a nice little piece of code.

Why Katas

The Merriam-Webster dictionary provides the following definition for kata

Kata

a set combination of positions and movements (as in karate) performed as an exercise

Most people are probably familiar with katas as they are used in martial arts (come on, admit it, you liked the Karate Kid).  My introduction to katas in software was through the Software Craftsmanship movement, where they are often used as training exercises.

It is important to understand with coding katas that the idea is not to do the exercises the same way every time.  Katas are a great way to experiment with different techniques and styles.

  • Can I provide more descriptive naming
  • Does a terse syntax make the code easier or harder to understand in a particular place.  Would a more verbose, explicit approach be better.  For example, in the case of a complex ternary operator, would an explicit structured if/else construct be better?  Worse?  Try them out and decide for yourself.
  • Experiment with different syntax, e.g. the unless keyword in Ruby.  More or less readable?
  • Should I use a defensive programming style checking for nil/null in several places or a more confident programming style?
  • How am I naming my tests (yes you should be writing tests as part of your katas)

There are no right or wrong answers to these questions, the goal is to experiment and try out new ideas.  Understand where an idea works well and where it doesn’t work well.  Try a variety of approaches.  And the great thing about a kata, unlike your code base at your real job, is that you can blow it away when you are done and do it a little different the next time.

Katas and Interviews

I’ve been using pairing as a key part of the interview process for several years now, but a consistent challenge is to what to pair on.  It is unrealistic to assume that most developers are going to walk in the door and instantly grok your code base.  No matter how awesome you are or how descriptive the tests are, it’s just not gonna happen. Instead pick a problem set that a candidate can quickly get their head around and that you can discuss different design and implementation choices.

Katas and Pairing

I had an awesome pairing session yesterday with someone I had never worked with before, and we did some katas as a way to get to know one another, discuss approaches to coding, good naming, refactoring techniques.  It was a blast!

And the really great thing about katas and pairing is that it can be challenging to think of different ways to try something on your own.  But with a pair you have different perspectives baked-in.  And what you can learn may not be strictly code related: it could be keyboard shortcuts, different IDEs or editors, maybe even a wacky keyboard.  Don’t be afraid to experiment.

Resources for Katas

Cyber Dojo
Great resource for ideas for simple exercises.  Even if you don’t use the online collaboration tools, it has a great list of problems that can be used for a kata.  I used this yesterday for my leap year kata in Ruby

Dave Thomas’s Katas
This is the blog post that kicked off a lot of the talk about katas in the software craftsmanship movement. Again, great problem sets that you can get your head around quickly, but with enough meat for some interesting challenges to address.

Your Friendly Neighborhood Software Craftsmanship Group
Here in Boston we have Boston Software Craftsmanship. Great group, someone’s always willing to pair.  Find your local group, or start one yourself.

Another Developer on Your Team
Ask someone on your team if they’d be interested in brown bagging it some day and do some kata’s together.  You should do this especially if you are not pairing now or are not doing TDD.  You may find that you should really be pairing and you really should be doing TDD.  You should.  Really.

CodeRetreat.org
I had a great time at last year’s Global Day of Code Retreat.  Check it out.  Conway’s Game of Life is a great coding exercise.  This also introduces some great constraints and pairing ideas that really get you thinking.

Now get out there and start coding…

So Ends The Season of Ruby

After a few false starts trying to get started with Ruby, I made a commitment this year to dive in with both feet and really learn it.  I decided on the notion of a “season” to dedicate to getting started with Ruby, and I think my initial dive has come to an end.  When are you ever done learning about a language or a technology, probably never?  And I am no more done learning about Ruby than I am done learning about C#, Java, Python, Perl, Javascript, or any other language.  Well, maybe Perl (ha, ha, ha).

So my introduction to Ruby and Ruby on Rails has not disappointed.  As expected, the community is vibrant and on the whole focused on real quality and craftsmanship.  There is no shortage of great resources out there to help a developer come up to speed on Ruby and Ruby on Rails.  And in that spirit, I wanted to take a snapshot on what I have learned, what resources I have found helpful, and where I might focus in the future.

Learn Ruby First

It is surprising easy to get up and running in Rails without really knowing much Ruby, just follow the wealth of examples and tutorials that are already out there.  I would argue strongly against that approach though.  Ruby has some really great features, especially if you are new to dynamic languages.  There is a an expressive syntax, great features like blocks and iterators, and incredibly rich set of standard libraries and 3rd party gems that allow you to build on.

Here are some of the resources I used to get up to speed with Ruby

Ruby Koans – Well structured introduction to the various features of Ruby.  A great intro to the language that you can bang through pretty quickly and refer back to when questions arise.  I have a lot of experience with Test Driven Development, but if you are new to TDD this will also get you thinking about TDD and how to write tests for your code.

The Pickaxe Book – Great resource on features of the Ruby language

The Ruby Way – Extensive resource for ways to solve several common programming tasks using Ruby.  This is also a great early introduction to writing in a Ruby-esque style, which was really helpful for me coming from C#.

Ruby-Doc.org is another good reference for features about Ruby, especially the core API and standard library.

Moving on To Ruby On Rails

There is just an incredible wealth of resources to getting started with Ruby on Rails.

I spent a lot of time on Michael Hartl’s Ruby on Rails Tutorial.  I loved the focus on TDD and good developer practices.  Other added benefits to this tutorial is it is a gently introduction to git and even shows you how to push your code up to heroku.  I know this is a resource I will continue to come back to again and again.

As much as I loved the Hartl tutorial, I wish I had actually started with Rails for Zombies.  Rails for Zombies is put on by Code School, which has a lot of content available for purchase, but the Rails for Zombies course will give you a good introduction to Rails and it’s free.  You can blast through it pretty quickly, gives you a good sense of the basics, and it really sets the table for a deeper dive into Rails.  I actually did this after spending a lot of time with the Hartl tutorial, but doing Rails for Zombies provided a lot of “a ha” moments as I went through it.

RailsCasts has a ton of great content, both free and by subscription and is just a fantastic resource.  The screencasts are typically anywhere between 5 and 15 minutes and cover a huge range of topics.

I can’t get enough of the Ruby Rogues podcast.  These guys do a fantastic job and have great chemistry.  I am shocked that they can do all of this every week, and it has made my commute a lot more educational and enjoyable.  They have some great guests and even for a newb I find the content informative.  Some stuff goes past me, but I usually go to the website afterwards and follow up on the links for the list of topics discussed on each episode.

Ruby 5 is another great podcast.  It serves a different purpose than Ruby Rogues.  Ruby 5 is more of a news oriented feed of what’s happening in the Ruby community, what gems have been released, what books have come out, etc.

Other great resources for learning about Rails are the Rails Guides and Rails ApiDock.

Get Involved in the Local Community

I am fortunate that in Boston there are a lot of resources for meeting and learning from other people in the community.

Boston Ruby puts on some great talks each month and also does hackfests a couple times a month.  I have been to a few talks, but really need to get to the hackfests. They also have a very active mailing list that is a great resource for technical issues.

The Boston Ruby on Rails group meets more sporadically, but seems like a great group.  I went there for a series of lightning talks just before starting the Season of Ruby and there was a spirited Q&A after each of the talks.  I am sure that helped motivate me.

I also went to a few workshops put on by thoughtbot that I got a lot out of: the Web Design and Development Process, and Intermediate Ruby on Rails.

Where to Next

The simple answer is just write more code because that is the best way I know to improve.  There is still sooooooo much to learn.