Browsing Posts published by james

Montreal skyline

A big thanks to everyone who attended my sessions earlier this week at DevTeach. When I give a presentation, my success criteria is that I get you excited enough to continue investigating the topic yourself. So an extra special thanks to all the attendees who took the time to talk to me afterwards. I obviously got some of you excited enough to continue learning what I was talking about! Awesome!!!

Another reason I love conferences is hanging with my peeps. I had a great time catching up with friends old and new in scenic, if somewhat cold, Montreal. Kudos to Jean-René Roy for putting on another fantastic conference.

Git Dojo

201212151800.jpgThe week started off with the fun-filled and action-packed Git Dojo with me on keyboards and Jessica Kerr on vocals and whiteboard. We even had a drummer, Howard Dierking, sit in for a set – attempting to wreak havoc on the repo when he .gitignore’d the Markdown files. The dojo was saved when he disappeared in a Spinal Tap-esque explosion midway through the set.

If you want to check out the Git Dojo yourself, you can clone the git-happens repo and follow along with the notes.

Emergent Architecture with TDD/BDD

201212151804.jpgI had a lot of fun with this session talking about the failure of UML as a design tool -though a great whiteboarding language. The holy grail of software design is the executable specification, which can be achieved with TDD/BDD. Executable specifications have the nice property of not only validating business requirements, but making it possible to validate non-functional requirements. I talked about some agile principles and techniques for good measure because that’s what I do. This led to the following tweet:

I’m not the first person to say this, but good to keep the idea circulating in our collective consciouses. 26 retweets and counting ain’t too bad. Happy to do my little part to make the software development world a better place for all of us.

I then talked about tools for creating executable specifications, specifically MSpec and SpecFlow (.NET) and RSpec and Cucumber (Ruby). We then dove into code with MSpec and SpecFlow because it was a more .NET crowd in the room. I especially loved the look of mild shock on some attendees faces when I executed what looked like a plain text file, which was in fact a SpecFlow/Cucumber file:

Shopping Cart Feature

The slide deck for Emergent Architecture with TDD/BDD is available here and the demos here.

Testable JavaScript

TestableJavaScript.pngAh, JavaScript… the red-headed stepchild of the language world. I talked a bit about the history of JavaScript and the increasing complexity of client-side applications as well as the recent rise of JavaScript on the server-side with Node.js. The need for JavaScript testing is more important now than ever. Fortunately there are some great testing/spec’ing frameworks available. I compared and contrasted QUnit, Jasmine, and Mocha. QUnit is wonderful for its simplicity, Jasmine excels at UI testing especially when paired with Jasmine-jQuery, and Mocha rules the roost for the elegance of its async testing support, which is no surprise given that it was born in the Node.js world. Regardless of which framework you choose, please please please give your client-side JavaScript code as much respect as your server-side code and write some tests/specs for it – preferably in a TDD/BDD fashion.

The slide deck for Testable JavaScript is available here and the demos here.

Coming Soon…

201212151852.jpgI’ll be presenting both Emergent Architecture with TDD/BDD and Testable JavaScript at CodeMash in Sandusky, Ohio, which is happening January 8 to 11, 2013. If you’re attending CodeMash, I’d love to see you in my sessions! Plus be sure to drop by and see me at the JetBrains booth where I’d be happy to teach you some ReSharper, RubyMine, or WebStorm ninja skills.

DeathMatch.jpgThanks to everyone who came out to my sessions at Prairie Dev Con in Regina last week. Once again, D’Arcy Lussier put on a great conference.

Testable JavaScript

The slide deck for Testable JavaScript is available here and the demos here.

ASP.NET MVC/Ruby on Rails Death Match

The slide deck is available here.

201209171918.jpgThank you to everyone who came out to my sessions at the NYC Code Camp. I had an awesome time and I hope that you did too. If you’re looking for resources and/or slide decks, you’ve come to the right place.

Testable JavaScript

The slide deck for Testable JavaScript is available here and the demos here.

Hands-On Git

The slide deck for Hands-On Git is available here.

A huge thanks to Steve Bohlen, Erik Stepp, Rachel Appel, and everyone else who helped out for putting on a great code camp. I’d also like to thank all the sponsors for their support in making community events like this possible.

SaintLouisSkyline.jpgI’ll be in Saint Louis, MO in mid-July to speak at the local Ruby and JavaScript user groups.

St. Louis Ruby User Group

Wednesday, July 18, 2012 @ 6:30pm

The Able Few LLC (2603 Cherokee Street, Saint Louis, MO)

TDD/BDD with RSpec and Cucumber

RSpec and Cucumber are the bread and butter of Ruby development. Learn how to write Cucumber features to drive out high level system behaviour. Then jump down into RSpec specifications to test-drive out the actual implementation of the system. See how outside-in development can improve your code and keep you focused on the problem at hand.

St. Louis JavaScript Meetup

Thursday, July 19, 2012 @ 6:30pm

The Able Few LLC (2603 Cherokee Street, Saint Louis, MO)

Testable JavaScript

Your client-side JavaScript is code as worthy of testing as any server-side code that you might write, but often JavaScript testing is ignored. This session will introduce you to QUnit and Jasmine, two popular JavaScript testing frameworks. Come see how you can easily incorporate TDD/BDD techniques into your web development stack and increase your confidence that your JavaScript code is as robust as your server-side code.

201207031557.jpgIn mid-August, I’ll be speaking at That Conference in Wisconsin Dells, WI. That Conference, which is being organized by Scott Seely and cohorts, is shaping up to be a lot of fun and has a fantastic line-up of speakers. I must admit that talking about That Conference with friends causes a lot of confusion. The conversation usually goes something like this:

Friend:
Which conference are you speaking at?
Me:
That Conference.
Friend:
Which conference?
Me:
That Conference.

Lather, rinse, repeat.

That Conference

August 13th – 15th, 2012

Kalahari Resort, Wisconsin Dells, WI

ASP.NET MVC/Ruby on Rails Death Match

In this corner, our first contender, weighing in at 35 kLOC of C#, we have ASP.NET MVC. In the other corner, weighing in at 168 kLOC of Ruby, we have Ruby on Rails. We’re going to see what it takes to build a web app – test-first – in both frameworks. We’ll compare and contrast their relative strengths and weaknesses. The goal is to give a balanced perspective on these two popular frameworks.

201207031600.jpgIn late August, I’ll be giving a number of Ruby-focused talks at devLINK in Chattanooga, TN. My friend and fellow vegan developer, Alan Stevens, has been bugging me for years to come speak at devLINK and I’m finally going. Very excited!

devLINK

August 29 – 31, 2012

Chattanooga Convention Center, Chattanooga, TN

Getting Started with Ruby on Rails

In this session, get a gentle introduction to the Ruby language and how to get started with your first Rails app.

Ruby without Rails

Ruby is about more than just Rails and web development. Ruby is a fascinating and powerful language that will put a smile on your face with its elegance. Come learn some Ruby.

ASP.NET MVC/Ruby on Rails Death Match

In this corner, our first contender, weighing in at 35 kLOC of C#, we have ASP.NET MVC. In the other corner, weighing in at 168 kLOC of Ruby, we have Ruby on Rails. We’re going to see what it takes to build a web app – test-first – in both frameworks. We’ll compare and contrast their relative strengths and weaknesses. The goal is to give a balanced perspective on these two popular frameworks.

If you’re at one of these events, don’t be a stranger! Come over and say hi. I’d love to see you there.

Recently I was doing a simple kata – the Roman Numeral kata – to practice my Ruby and RSpec skills. (The Roman Numeral kata is to build an algorithm test-first that converts a number into its Roman numeral equivalent. For example, 1 to i, 7 to vii, 10 to x, etc. The problem is intended to be simple so that you can focus on the process.) I had the following RSpec code:

require 'roman_numeral'

describe RomanNumeral do
  # specify is just an alias for it. specify reads better in this case
  specify '1 should be i' do
    numeral = RomanNumeral.new(1)
    numeral.to_s.should == 'i'
  end
end

I go through the Red/Green/Refactor cycle and get this first spec working. (I won’t show the production code as it’s not that interesting.) I move onto the second spec.

require 'roman_numeral'

describe RomanNumeral do
  specify '1 should be i' do
    numeral = RomanNumeral.new(1)
    numeral.to_s.should == 'i'
  end

  specify '2 should be ii' do
    numeral = RomanNumeral.new(2)
    numeral.to_s.should == 'ii'
  end
end

Red/Green/Refactor and all is good. But I’m seeing some repetition in my specs and it’s only going to get worse. The specs are almost identical except for the data. So I start hunting through the RSpec docs for something akin to NUnit’s [TestCase] or xUnit’s [Theory]. I find nothing. Maybe, like MSpec, RSpec wasn’t designed to do this sort of data-driven testing.

Undaunted I turn to Google and stumble upon this StackOverflow question asking exactly the same question that I had. Matt Di Pasquale, the OP (original poster), found his own answer and that answer was fascinating! No, RSpec doesn’t have a syntax for test cases because it doesn’t need one. Use the Ruby, Luke!

require 'roman_numeral'

describe RomanNumeral do
  cases = {
    1 => 'i',
    2 => 'ii'
  }

  cases.each do |k, v|
    specify "#{k} should print as #{v}" do
      numeral = RomanNumeral.new(k)
      numeral.to_s.should == v
    end
  end
end

For those not as well-versed in Ruby, “cases” is simply a variable that contains a hash. I then iterate over the key/value pairs and define my specifications. It’s that simple. I didn’t need any special attributes or framework support from RSpec. I didn’t need to learn the inner workings of RSpec to write my own custom extension or attributes. I simply wrote some Ruby code. Let that sink in for a second. I simply wrote some Ruby code.

Now think about that a bit more. I’m writing regular Ruby code to implement the notion of test cases. Rather than defining test cases, I could have used very similar code to define a benchmark that verifies an algorithm scales linearly with number of input elements. Or I could have fuzz tested an external API for my application. The possibilities are only limited by my imagination and don’t require me to gain an ever deeper understanding of my testing/specing framework to implement.

For someone who cut his teeth on C, C++, and C# (with some JavaScript thrown in for good measure) and is used to learning (or building) frameworks to solve problems, the notion that you can just write plain old code to solve these types of meta problems is eye-opening. It is one of those ah-ha moments that matures you as a developer. Not every problem needs a framework to solve it. Sometimes it just requires a little code.

factory_girl.jpgAs some of you might have noticed, I’ve been talking about Ruby and Ruby on Rails more recently. It’s often good to get outside your comfort zone and see how other (web) developers live. One of the areas where Ruby really excels is the wealth of innovative testing/spec’ing libraries available. When writing tests/specs, we need objects to play with. Ruby has a variety of options in this regard, but I particularly like the factory approach espoused by gems such as factory_girl or machinist. I’m partial to factory_girl. So let’s take a look at the syntax and see if we can create something similar for .NET. First off, let’s take a look at the usage syntax:

describe Site do
  it "should register a new user" do  
    user = FactoryGirl.build(:user)
    site = Site.new
    site.register(user)
    site.users.should include(user)
  end
end

If we want to customize the instance, we can do that too by passing in a hash as the second argument:

describe Site do
  it "should not register new admin users" do
    user = FactoryGirl.build(:user, :admin => true)
    site = Site.new
    site.register(user)
    site.should_not include(user)
  end
end

What is interesting about factory_girl is that we can create instances of objects without the visual clutter of irrelevant properties. A user requires a first and last name, but in the above cases, we don’t care what they are. In the second case, we can see that the user being an admin is important for this test/spec. By removing the irrelevant properties, we can quickly see at a glance the data that matters for this spec. We also have the advantage that as properties are added to the User class, we have one place to update them (e.g. in the factory_girl definition) and we don’t have to wade back through all our tests adding values for required properties.

ASIDE: Now you might be tempted to say that we’ve been doing something like this in .NET with the Object Mother pattern. The Object Mother pattern is a factory of sorts. The problem is that it tends to be a dumping ground for different variations of the test objects. For example, ObjectMother.CreateUser(), ObjectMother.CreateAdminUser(), ObjectMother.CreateUserWithFirstName(string firstName), ObjectMother.CreateAdminUserWithFirstName(string firstName). The result is a tightly-coupled big ball of testing mud where the team is loathe to re-use ObjectMother methods for fear of breaking other tests. So you end up with this sprawling mass of methods for creating test data, which is separated from the tests themselves. Not a good place to be in.

Let’s look at the syntax for defining our factories in factory_girl:

FactoryGirl.define do
  factory :user do
    first_name 'John'
    last_name  'Doe'
    admin      false
  end
end

There is a lot more to factory_girl than I’ve covered above. When defining factories, you can create associations, lazy attributes, aliases, sequences, callbacks, and much more to keep your factories clean, lean, and mean. When using the factories, there is more than just FactoryGirl.build. There is also FactoryGirl.create, which saves the built instance to the database, FactoryGirl.attributes_for, which provides you with a hash of values often useful for testing Controller create actions, and FactoryGirl.build_stubbed, which returns a stubbed out instance. Here we’re going to focus on FactoryGirl.build to see how close we can get to the Ruby syntax, but written in C#.

Let’s start by looking at what our definition syntax could look like in C#.


FactoryGirl.Define(() => new User());


We give FactoryGirl a Func<T> that creates an instance of the object. Note the use of C# type inferencing so that we don’t have to specify the generic method argument on FactoryGirl.Define.


public static class FactoryGirl {
  private static readonly IDictionary<Type, Func<object>> builders = new Dictinonary<Type, Func<object>>();

  public static void Define<T>(Func<T> builder) {
    if(builders.ContainsKey(typeof(T))) throw new DuplicateFactoryException();
    builders.Add(typeof(T), () => builder());
  }
}


Basically I’m just keeping a hash table of Type versus Func<T>. That way when I get asked to build an object later, I can look it up and run the Func<T>. I have to play some games with the C# type system. My hash table has to store Func<object> because the generic parameter is declared on the methods, not the class. C# is also not able to implicitly convert Func<T> to Func<object>. So I have to add a lambda to the hash table that calls the builder rather than adding the builder directly.


builders.Add(typeof(T), builder); // Compiler error


Whereas the following makes the C# compiler happy.


builders.Add(typeof(T), () => builder()); // Compiler is happy


Now let’s look at the API for building an object.


var user = FactoryGirl.Build<User>();


From an implementation standpoint, we simply need to find the appropriate Func<T> and execute it.

public static class FactoryGirl {
  public static T Build<T>() {
    return (T) builders[typeof(T)];
  }
}


Simple enough. Now if we want to customize the object built…


var admin = FactoryGirl.Build<User>(x => x.Admin = true);


We really just need to accept an Action<T>, which we will execute after the object is constructed.

public static class FactoryGirl {
  public static T Build<T>(Action<T> overrides) {
    var result = (T) builders[typeof(T)];
    overrides(result);
    return result;
  }
}


With this simple implementation, we now have a central place to define our factories and build objects. Any customizations required are in the tests/specs themselves making it easier to understand our intentions in the tests/specs. When we add a new required property, we need to simply update our factory definition with an appropriate default. If needed, you can easily call FactoryGirl.Build() from within a factory definition. I have used this FactoryGirl technique in a production application and it dramatically cleaned up our specification code as compared to a previous project that used Object Mother. I hope it gives you some ideas of how to clean up your own test/spec code. If you are curious about the code or interested in extending FactoryGirl.NET to add some missing capabilities, such as Create, AttributesFor, BuildStubbed, or anything else, you can find the code on GitHub.com here.

UPDATE: A few people have asked me about customizing multiple properties when building an object. FactoryGirl.NET already supports this using the following syntax:

var user = FactoryGirl.Build<User>(x => {
                x.Admin = true;
                x.Age = 42;
           });

logo.gifTo say that I’m a big fan of JetBrains is a bit of an understatement. I’m always talking about ReSharper, dotTrace, dotCover, dotPeek, TeamCity, and many other JetBrains products in person, on Twitter, on my blog, in talks, … Many years ago I released a (now-defunct) ReSharper test runner plug-in. (Defunct because the functionality is now included in ReSharper itself.) I’m one of a team of people running http://teamcity.codebetter.com, which is a widely-used OSS build server run by CodeBetter.com and Devlicious.com in collaboration with JetBrains. I’m on the board of the JetBrains Development Academy. I was JetBrains booth babe/demo monkey at PDC a few years back. I authored the ReSharper course for Pluralsight. (N.B. Through a cross-promotion deal, JetBrains includes one-month access to my Pluralsight ReSharper course for new and existing ReSharper users.) I’m sure there are things that I’m forgetting.

Recently JetBrains approached me about joining their team as a technical evangelist. I was flattered and honoured at being considered for such a position. Then came the hard questions…

Me: I don’t want to be pushing products for the sake of products.

JB: We don’t want you to. We want you to evangelize software best practices and talk about where JetBrains products make developers’ lives easier.

Me: My interests extend beyond .NET. I’ve also done a lot of JavaScript and web work. Plus I’ve been getting into Ruby and Ruby on Rails a lot recently. And I’d like to do some iOS development.

JB: That sounds great! As you know we’ve got products in all those areas and can use someone with that kind of breadth.

Me: I don’t want to put Hadi out of a job.

JB: No worries. You’ll be Hadi’s counterpart in North America. We’ve got enough to keep both of you busy for a long time.

So Hadi and I will be working closely with the rest of the JetBrains team to bring you more awesomeness from JetBrains. More awesome blog posts. More awesome screencasts. More awesome presentations. And of course more awesome information about JetBrains products. (Let’s be realistic. We’ve all got mortgages/expenses to pay.) If you have questions, comments, or quibbles about JetBrains products – especially how we can make them better – Hadi and I are the people you want to talk to. And we want to talk to you, our community.

Canadian Maple LeafTo answer a few burning questions that I’m sure people have… I’ll still be based out of Calgary, Alberta, Canada. I’ll still be speaking at various conferences and user groups – and not just about JetBrains products. (It will be the usual mix of software practices, development techniques, and technologies. So expect to see me at conferences and events both as a speaker and representing JetBrains.) I’ll still be producing Pluralsight videos. (NHibernate Fundamentals will be available soon and I’m already work on Git Fundamentals. JetBrains and Pluralsight will continue to partner on various initiatives.) I’ll still be involved in open-source software. And I’ll still be causing the usual amount of trouble on Twitter and elsewhere. Happy coding!

InfoQ has made another of my DevTeach talks available online – TDD/BDD as Architectural Tools. Enjoy!

TDD/BDD as Architectural Tools

As architects, we have all experienced the folly of BDUF (Big Design Up Front) – spending weeks or months perfecting an architecture that fails when it meets the real requirements and real code. Is it possible to design in the small? How can we avoid unintended complexity, which cripples so many code bases? Can we build enough of an architecture to start writing code and then flesh out our architecture as the code evolves? In this session we examine how Test-Driven Development (TDD) and Behaviour-Driven Development (BDD) allow us to solve these conundrums. We will see how we can use TDD/BDD to focus our architectural efforts in the high-value areas of our code base to achieve just-in-time architecture.

A friend just pointed out that my presentation on “Convention-over-Configuration in an Agile World” is being featured by InfoQ. (The speaker is always the last to know.) I’m honoured and humbled by the great responses from folks. Worst criticism so far is that the presentation isn’t about TDD/BDD. Well, it’s not. Here is my original description:

Convention-over-Configuration in an Agile World

As developers, we spend an inordinate amount of time writing “glue code”. We write code to transform database rows to domain objects… domain objects to view-models or DTOs… We write code to configure inversion of control containers and wire dependencies together. We write code to style our UIs and respond to UI events. Wouldn’t it be nice if this could happen automagically for us? This session will look at using convention-based approaches using Fluent NHibernate and Castle Windsor to reduce the amount of repetitive code and accelerate application development.

So check it out and let me know what you think…

A question I often get asked is why psake does not include something similar to NAnt’s <replacetokens>. The reason is because it’s so darn easy to do it in PowerShell. Given foo.txt.template:

@@foo@@ is @@bar@@!!!

The following script will perform the replacement:

# replace.tokens.ps1
$foo = 'PowerShell'
$bar = 'da bomb'
(cat foo.txt.template) -replace '@@foo@@', "$foo" `
                       -replace '@@bar@@', "$bar" `
                       > foo.txt

(Note the backticks (`) at the end of the line to denote continuation.)

This script will produce:

PowerShell is da bomb!!!

You could easily write a function that would take care of the nitty gritty details. The @@var@@ is arbitrary. You could use any sequence you like. You can even perform regex matches in the @@var@@ expression if needed. Note the double quotes around "$foo". This is PowerShell for performing variable replacements in strings. So "$foo" results in the word PowerShell whereas ‘$foo’ results in the word $foo.

So there you have it. Token replacement built right into PowerShell. Happy Scripting!