Browsing Posts published in March, 2012

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 =
    site =
    site.users.should include(user)

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 =, :admin => true)
    site =
    site.should_not include(user)

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

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 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 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)];
    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 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, which is a widely-used OSS build server run by and 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!