Implementing case-insensitive lookup tables (Dictionary) with string keys

The Dictionary type in .Net takes in a comparer as a constructor parameter. So you could pass in StringComparer.OrdinalIgnoreCase and you're done.
I used to upper-case keys while adding it to the lookup table earlier and again when performing a lookup - to achieve case-insensitive string lookups. I remember reading some article about String.ToUpper() being optimized for such scenarios. Now I was unsure - which one is better ?

WPF - Find a child control of a specific type or satisfying a given predicate under a parent control

Ideally you shouldn't be doing this in WPF and MVVM land. However there is an exception to every rule.. mine was I had to set the focus and put a specific cell in a grid into edit mode when the user clicked a button.

Set keyboard focus when the user begins editing a wpf datagrid templatecolumn ?

The problem:
When I begin editing a grid cell, I'd expect the keyboard focus to be set the edit control for the cell. In case of a textbox, I'd also like the existing contents to be selected by default ; so that i can begin typing and set a new value quickly.

Humanized's Enso Launcher : Jumpstart

Enso is a good example of the axiom that 'Search is faster than navigation'. Its one of the tools that I was introduced to by the book 'The productive programmer' by Neal Ford. It has been handy ever since.

The concept of the tool is pretty simple... it redefines the way in which you communicate with your machine. e.g. If I want to install or uninstall a program, I do not want to click through a number of windows and dig through menus (and lose my focus by the time I get there). My intention is 'open add or remove programs' so that I can install that new app. It may be a tiny boost but multiplied by the volume of instances / day, Enso can save you a lot of time. So lets get right to it...

First you need to install Humanized's Enso launcher (12 MB download)
Next it's easier if you are a keyboard person instead of a mouse person. You need some dexterity with your left pinky finger

Enso takes over your capslock key once installed. So keep capslock pressed down with your left pinky (you should see a green floating band at the top-left) and continue typing to issue commands....

Opening/Launching programs

With Vista and Windows7, this is not something to write home about. Both of them have a real-time search box when you invoke the Start Menu - where you can enter a substring/part of the app you want to invoke and the start menu narrows down your choices.

However if you're on WinXP, you're gonna love this. e.g I always had to go hunting for the add/remove programs applet inside the Start Menu. (or pick something else e.g. like a specific version of Visual Studio). Soon I'd be piling on quick launch icons ; and even that required you to reach for the mouse. (I like to be one with the keyboard as long as possible).

Now with enso, reach out your left pinky to the capslock key. Keep it pressed, while you continue to type a substring e.g 'open remove' or 'open 2008' in the green floating band that just popped up. You'll see a dynamically updating dropdown that you can use to select with the arrow keys. When you lift your finger off the capslock key. The selected program shall be opened. No kidding... try it. It's addictive ; No program is ever more than one open command away.
Useful: Absolutely

Associate a file/directory/url/shortcut with a command

Assume you have a directory that you frequently access e.g.
d:\mail\snail\wail\jail
Ensure that the above path is selected (either in the location bar of windows explorer or write it down in notepad and select it). Next use your pinky and type in
learn as open jail
Enso should get back with 'open jail is now a command'

Now try opening like before.
Caps + 'open jail'
and you should see a windows explorer window pointed at the right folder.

You just taught Enso a new command 'jail'.
You can verify this by looking in your MyDocuments folder. You should see a folder created by Enso with all your commands.
This also means that you can carry your enso commands with you across machine (e.g. in a USB storage device), dump it to the local MyDocuments folder and off you go.

Of course Enso just takes over your capslock key, to regain that function, Enso has 2 commands. Keep caps pressed and type
'capslock on' OR
'capslock off'.


You can make Enso unlearn a command by saying
Caps + 'unlearn open jail' Enso wipes its memory cells clean.
Useful: Usually. e.g. you could associate your MRU visual studio solution file with a command 'curproj'

Now try this on selected files/shortcuts.
e.g. Select any exe or shortcut in your file explorer.
Caps + learn as open someexe
Now you can the exe is at your fingertips with
'open somexe'
Works for shortcuts too. You can even create a "rooted view" e.g. create a shortcut for %windir%\explorer.exe /e, /root, D:\tarpit\theNextKillerApp
Select it and learn it as a command. Try it out
Useful: Sometimes

Works for urls as well. Enso would open up your a new instance/tab of your default browser pointed at the learned url.
e.g. select http://www.answers.com/topic/dexterity right here. Teach enso a new command
Caps + 'learn as open dex'
Now you can open this page at any time using
open dex

Useful: Occasionally - since browsers have generally better at this; bookmarks, tags and incremental search in the address bar.

Jump/Switch to an open window or tab in a browser

This one is nice.
Caps + 'go google'
or
go taskjump directly to an open window which has that substring in the window title.
Its works for browser tabs too - if you had a minimized or buried browser with a tab showing google's homepage, the right browser and child tab would be activated. Its a shame it doesn't work with Firefox3.. seems to be a bug that could be fixed. Works with IE8
Useful: Pretty much ; wish I could unlearn alt+tab-ing as easily as Enso.

Open with ...

This one is supereasy but hasn't become second nature to me yet. You can select any file (e.g. in a file explorer)
Caps + 'open with [name of app]'

and Enso does just that. e.g. 'open with notepad' will open up the selected file in notepad.
Useful: Yes. No more Shift+right click > Open with ... > hunt for the exe if !inList. Freedom!!

Close active window/tab

the command is close. I like dismissing windows with
Caps +'cl'
Enso can do minimize and maximise too.

For more inbuilt commands, Use Caps + 'command list' to have a look at inbuilt commands. I believe you can script custom commands too (e.g. 'mail' instead of 'open Outlook') if you know a bit of Python. However that's outside the scope of this post :)

That's all folks!

HOW TO : Setup your Xtreamer to stream content off Windows (Win7) machines via a wifi network

Update#2 [Apr 2010]: Sent the wireless USB dongle back to their seller in India since it was within the warranty period. They sent me a new dongle, free of cost. Now the whole setup is functional again. The online forum on the other hand was another deal altogether...

Update: My Xtreamer has stopped communicating via wifi after 3 days, without any configuration changes. "Can't get SSID" is the only response I get from the network settings page. The Wifi antenna drivers are proprietary (available for download) and hence I can't isolate the problem to the antenna. 2 subsequent posts to the Xtreamer forum have been mysteriously being deleted without any dialogue/clarification. Verdict as of now: Flaky antenna/connection finder.. wouldn't get this if streaming is your main need.

This post details my skirmishes in getting my Xtreamer (a streaming media player) to wirelessly stream content off my Windows7 laptop via a DLink N-Router. You could hook it up such that the Xtreamer can also access the internet - but I haven't done that. I intend to use the Xtreamer on a local trusted network and internet access on a diff public wireless network.

NUnit ExpectedException Bug in 2.4.7

"Bug In NUnit ? It can't be!" Exactly my words ; However it turned out that the behavior is due to a newer NUnit runner (Gui v 2.5.3) running a test fixture referencing an older version of NUnit.Framework.dll (v2.4.7)

Try this in a NUnit test fixture referencing NUnit.Framework v 2.4.7


// 2.4.7 - test passes even if an exception of wrong type is thrown
[ExpectedException(ExceptionType=typeof(FileNotFoundException))]
[Test]
public void Test_ExpectedException()
{
throw new ArgumentException();
}


I found that the test passes if "any" exception is thrown. It doesn't have to match the specified type. A false positive!

To fix this, upgrade your NUnit version to 2.5.2. You'd also need to fix a compile error. 'ExceptionType' property has now become ExpectedException.


//2.5.2 'works as expected'
[ExpectedException(ExpectedException=typeof(FileNotFoundException))]
[Test]
public void Test_ExpectedException()
{
throw new ArgumentException();
}



You live... you learn.

Method resolution in Ruby : OR how to find Mr. Right method?

Before I begin: Some of the stuff below may be incorrect (Corrections welcome.), however it helps me understand ruby method resolution. I have come up with this model based on my reading of the RubyProgrammingLanguage book (must-read for anyone learning Ruby) by Flanagan & Matz and some tinkering.. it may not be accurate (if that is what you're after)


Basket of Facts:
  • A Ruby type is an object of type 'Class' (henceforth referred to as a class-object)
  • An object has a class attribute pointing to the right class-object.
  • An object has an "eigenclass"/"metaclass" that holds singleton methods (methods that are only available to that instance.)

class-objects are special in a few ways:
  • a class-object has its class attribute pointing to the 'Class' type in Ruby
  • a class-object has a superclass
  • the "eigenclass" of a class-object also has a superclass; the eigenclass of its superclass
  • a class-object has an included modules list
  • a class-object has a table of methods (instance methods defined in the class definition)
  • class methods are singleton methods of the class-object
  • a class-object is generally associated with a constant viz. it's class name.



So now let's get started. Don't let the following mouse-drawn picture scare you - it'll all make (some?) sense in sometime. In the meantime, right click on it and open it up in a new tab and have the picture handy for reference while you descend into this post.



Next jump right over this big puddle of source code. You can copy it into your editor if you want to try it out with me..

module Kernel
def breadcrumb
puts "Kernel#breadcrumb"
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end
end
class Object
def breadcrumb
puts "Object#breadcrumb"
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end
def self.breadcrumb
puts "Object.breadcrumb"
class << Module.nesting[0]
instance_eval { remove_method :breadcrumb }
end
end
end

module MyModule
def breadcrumb
puts "MyModule#breadcrumb"
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end

end

class Base
MY_CONST = :b
include MyModule

def breadcrumb
puts "Base#breadcrumb";
Base.class_eval{ remove_method :breadcrumb }
# Base.instance_eval{ remove_method :breadcrumb } UH-OH! why does this remove the inst method
end
def self.breadcrumb
puts "Base.breadcrumb"
class << Module.nesting[0]
instance_eval{ remove_method :breadcrumb}
end
end
end

class Derived < Base
def breadcrumb
puts "Derived#breadcrumb";
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end
def self.breadcrumb
puts "Derived.breadcrumb"
class << self
instance_eval{ remove_method :breadcrumb}
end
end
end

class Class
def breadcrumb
puts "Class#breadcrumb";
Class.class_eval{ remove_method :breadcrumb }
end
end
class Module
def breadcrumb
puts "Module#breadcrumb";
Module.class_eval{ remove_method :breadcrumb }
end
end



****LANDING ZONE****
Nice Jump!

I have defined a new class called 'Derived' which derives from 'Base' and includes 'MyModule'.
Unless a base type is explicitly specified, all classes derive from Object (which includes Kernel) (and derives from BasicObject - new in Ruby 1.9). e.g. Base derives from Object. This can be verified via


d = Derived.new
p d.class.ancestors # => [Derived, Base, MyModule, Object, Kernel, BasicObject]



Base and Derived each have defined a class method (self.breadcrumb) and an instance method (breadcrumb). MyModule just defines a module method of the same name.
Convention: Class/Singleton methods would print receiver.breadcrumb. Instance methods would print receiver#breadcrumb.

Take a deep breath and dive in...

First lets create a new instance of Derived and add a singleton method to it. (i.e. a method that is present only in that instance. Another instance of Derived would not have this method)
Here's how we do that...


d = Derived.new

class << d
def breadcrumb
puts "DerivedObj[id:%d].breadcrumb" % object_id
class << self
instance_eval{ remove_method :breadcrumb}
end
end
end


'Call once': once the method is called, the method disappears (is 'undefined'). This will help us uncover the order in Ruby tries to find a method. I have added such methods in all types up the hierarchy (and then some) to help us spot the trail.
(Note: Instance methods use class_eval to remove themselves. Singleton/class methods use instance_eval. Refer to the RPL book)

And now for the moment of truth


puts "Method call on an object".center(40, "*")
6.times{ d.breadcrumb }


Output:
********Method call on an object********
DerivedObj[id:6186928].breadcrumb
Derived#breadcrumb
Base#breadcrumb
MyModule#breadcrumb
Object#breadcrumb
Kernel#breadcrumb


Refer to the image (I was reading Why's Nobody know Shoes; which might explain some of the weird imagery and the helpfulness of it all ;) So here's what happened in the sequence illustrated by our 'call-once' breadcrumbs:

To the extreme left is our object d,
  • Call1: Find the eigenclass of d, look for a singleton method of that name. Found!
  • Call2: .. not found in eigenclass, find the class-object of d via the class attribute. Look in the methods defined in class Derived. Found!
  • Call3: .. not found in eigenclass/class. Look in included modules of D (most recently included one first).. there are none. Travel via the superclass portal to reach Base. Look for inst method. Found!
  • Call4: .. not found in eigen/class/incl module/superclass. Try included modules of superclass e.g. MyModule. Found!
  • Call5: .. not found in eigen/class-n-its-modules/superclass-n-its-modules. Go down the superclass portal again to reach Object. Look at instance methods. Found!
  • Call6: .. look in incl. modules of Object. Kernel. Found!



If you try calling the method again, Ruby would not be able to find a method of that name and would now try looking for a method_missing method (in the same manner as it tried looking for breadcrumb. However this time it is guaranteed to find it because Kernel has a method_missing implementation that raises the NoMethodError. Need to see it to believe it?


temp.rb:84:in `block in
': undefined method `breadcrumb' for # (NoMethodError)
from temp.rb:84:in `times'
from temp.rb:84:in `
'


So lets recap the steps.
1. Look in the eigenclass (golden arrow) for the class
2. If not found, traverse the class attribute (purple arrow) to find the class-object.
3. Look in the instance methods for this class
4. If not found, try included modules of the class (in reverse order of mixin)
5. If not found, check if we have a superclass (pink arrow). If yes, repeat steps 3-5 till we run out of superclasses
6. If still not found, go back to Step1 but this time look for a 'method_missing' method'


By the way, we just saw how instance methods are inherited. (Snuck that one on you.) If Derived doesn't define an instance method, all its ancestors are looked up in order ; inheritance works.

Take a break, have some lemonade before we set out again... Ready? Off we go again. This time instead of calling a method on an object, we call a class method. Comment the previous 2 lines...


puts "Method call on a class-object".center(40, "*")
7.times{ Derived.breadcrumb }


Output:
*****Method call on a class-object******
Derived.breadcrumb
Base.breadcrumb
Object.breadcrumb
Class#breadcrumb
Module#breadcrumb
Object#breadcrumb
Kernel#breadcrumb


Hey! we see some instance methods being invoked when we call a class method. What the... Deep breaths 1..2..3..pfffhoooo (u got to get the pfffhoooo right)

Let's see if our image can help us out, find the object pointed to by the constant Derived (3rd box from the left - first row)

  • Call1: Start at Derived. Follow the golden arrow to the Derived's eigenclass - Derived". Look for a singleton method. Found!
  • Call2: .. not found in eigenclass. But eigenclasses of class-objects have superclasses. Follow the golden arrow to Base's eigenclass. Found!
  • Call3: .. not found in Derived" or Base". But we still have a golden arrow to Object". Found!
  • Call4: .. not found in Derived"/Base"/Object".Try BasicObject" too. Not found. Now we're out of superclasses. Now we follow the purple arrow to the class-object of Derived i.e. Class. Look for instance methods defined there. Found!
  • Call5: .. not found in the eigenclass hierarchy or class-object. Try included modules in Class. not found. But wait, we have a superclass. Down the pink arrow to Module. Look for an instance method... found!
  • Call6: .. not found in eigenclass hierarchy/Class-n-included-modules/Module. Try included modules in Module. Nope. Down the pink arrow to Object. Found an instance method!
  • Call7: .. not found in eigenclass hierarchy/Class-n-incl-modules/Module-n-incl-modules/Object. Look in included modules of Object.. aha Kernel. Look for method.. found!



If you make one more call, you should now be guessing that a NoMethodError should show up from Kernel#method_missing(similar to the previous example)

So lets refactor the steps.
  1. Look for the method in the eigenclass (yellow arrow). Until we run out of superclasses for the eigenclass, inspect each eigenclass for the method.
  2. If not found, traverse the class attribute (purple arrow) to find the class-object.
  3. Look in the instance methods for this class
  4. If not found, try included modules of the class (in reverse order of mixin)
  5. If not found, check if we have a superclass (pink arrow). If yes, repeat steps 3-5 till we run out of superclasses
  6. If still not found, go back to Step1 but this time look for a 'method_missing' method

So the only new tidbits were
  • class methods are singleton methods of class-objects. They live in the green clouds tied with the yellow arrows to the class.
  • eigenclass of a class-object is special. These special 'green clouds' have superclasses.
And that is the secret behind class method inheritance... See the first three lines of the output. (Snuck another one.. {snicker} No more I promise.)

And that also explains how class method calls can result in instance methods being called. (Lines4-7)

And that's it folks! You will wake up enlightened or confused when I snap my fingers :)


As an exercise to people who like to stay and flex some meta-programming muscles. Try and explain this predicament.

Module defines a constants method, which returns the list of all known constants (incl. class names).
Module.constants => 102
Any user-defined class e.g. Base or Derived inherits this method ; however Base.constants returns only the constants defined inside Base (and its superclasses). e.g. If I add a constant inside Base.
Base.constants => 1
How does Module's constants behave differently in the Base (which inherits this functionality)?

Hint: Check Module.singleton_methods and Module.public instance_methods
Hint2: Hit Stackoverflow and search for the answer once you have taken a good crack at it.

Meet the frameworks : Rhino v Moq v jMock : Part II

Story so far
We've seen how to
* setup expectations for calls on methods/properties.
* specify the number of times to be called.
* specify values to be returned

Now I move onto more involved scenarios.

#6:Throw an exception in response to an expected call on mockCollaborator.Method()
  • Rhino Mocks


[ExpectedException(ExceptionType=typeof(UnableToServeException),
MatchType=MessageMatch.Contains,
ExpectedMessage="Sorry for the inconvenience.")]
[Test]
public void Test_ExpectExceptionToBeThrown()
{
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false)).Throw(new Exception());

_bakery.PlaceOrder(OrderForOnePineappleCakeNoIcing);
}

The Throw method tagged onto the end of the Expect does the trick of raising any derivation of Exception (here I've raised a generic Exception)
  • Moq


[ExpectedException(ExceptionType=typeof(UnableToServeException),
MatchType=MessageMatch.Contains,
ExpectedMessage="Sorry for the inconvenience.")]
[Test]
public void Test_ExpectExceptionToBeThrown()
{
_mockChef.Setup( chef => chef.Bake(CakeFlavors.Pineapple, false)).Throws<Exception>();
_bakery.PlaceOrder( OrderForOnePineappleCakeNoIcing );
}

Moq uses a generic Throws() to achieve the result
  • jMock


@Test
public void test_expectAndThrowException() throws OutOfIngredientsException
{
final Sequence aSequence = context.sequence("retryBake");
context.checking( new Expectations() {{
oneOf(_mockChef).bakeRealWorld( CakeFlavors.Pineapple, false );
will(throwException(new OutOfIngredientsException() ));
inSequence(aSequence);
oneOf(_mockInventory).replenishStocks();
inSequence(aSequence);
oneOf(_mockChef).bakeRealWorld( CakeFlavors.Pineapple, false );
inSequence(aSequence);
}});

_bakery.placeOrderRealWorld( OrderForOnePineappleCakeNoIcing() );
}

The will(throwException(exceptionInstance) after an expectation does the trick. Ignore the lines in Sequence (I'll get to them in Section#9)

Java's checked exceptions and explicit method specification (all the way up the call-chain) feels a bit too rigid to me (maybe due to my .Net exposure). So I've created an overload of Bake that throws an exception, to avoid adding a throws clause to every test method that has an expectation for Bake(). Worked for me.. although it's not the right thing to do. The joys of coding in a toy example!

void bakeRealWorld(CakeFlavors flavor, boolean withIcing) throws OutOfIngredientsException;


#7:Custom callbacks or blocks of code to execute when a mockCollaborator.Method() is called
Let me cook up a use for this. Let's say I want the first call to Chef.Bake throw an OutOfIngredientsException(), so that I can call ReplenishStocks() and retry. This time, the call to Chef.Bake should go through.

Just the kind of job for... custom Callbacks!

  • Rhino Mocks


[Test]
public void Test_ExpectWithCustomCallback()
{
int callbacks = 0;
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Repeat.Times(2)
.WhenCalled(delegate(MethodInvocation mi) {
Console.WriteLine("Callback Params: {0}, {1}", mi.Arguments[0], mi.Arguments[1]);
callbacks += 1;
if (callbacks == 1)
throw new OutOfIngredientsException();

return;
});
_mockInventory.Expect(inv => inv.ReplenishStocks()).Return(true);

_bakery.PlaceOrder(OrderForOnePineappleCakeNoIcing);

_mockChef.VerifyAllExpectations();
_mockInventory.VerifyAllExpectations();
}

Tag on WhenCalled(delegateWithCustomCode) to the expectation. Also note that you have access to the method arguments as shown in the Console trace above.
  • Moq


[Test]
public void Test_ExpectWithCustomCallback()
{
var callbacks = 0;
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Callback( delegate(CakeFlavors flavor, bool withIcing)
{ // any custom code
Console.WriteLine("Callback Params: {0}, {1}", flavor, withIcing);
callbacks += 1;
if (callbacks == 1)
throw new OutOfIngredientsException();

return;
}
);

_mockInventory.Setup(inv => inv.ReplenishStocks()).Returns(true);
_bakery.PlaceOrder( OrderForOnePineappleCakeNoIcing );

_mockChef.VerifyAll();
_mockInventory.VerifyAll();
}

Tag on an overload of Callback( customDelegate ) at the end of the Setup to specify custom code to be executed.
Moq gives you strongly typed callbacks with upto 4 parameters (Action is the biggest Action type in .Net; a restriction that will be lifted with .net 4.0). Argument access is a snap.

  • jMock


// http://www.jmock.org/custom-actions.html
@Test
public void test_expectAndInvokeCustomCallback()
{
context.checking( new Expectations() { {
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false );
will( MyCustomCallback.tracingCallback() );
} } );

_bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 1) );
}
class MyCustomCallback implements Action
{
public void describeTo(org.hamcrest.Description description)
{
description.appendText("a custom callback to do what I deem fit! ");
}

public Object invoke(Invocation invocation) throws Throwable
{ // any custom code
System.out.println("Callback invoked with "
+ ((CakeFlavors)invocation.getParameter(0))
+ " and "
+ (((Boolean) invocation.getParameter(1)).booleanValue() ? "" : "no")
+ " icing!");
return null;
}
public static Action tracingCallback()
{
return new MyCustomCallback();
}
}

It may be due to my rusty Java but it turned out to be a whole lot of classes to achieve this with jMock

#8:Raise an event from a mock collaborator
This one is very handy when testing GUIs using a ModelViewPresenter (or related pattern)

Our inventory raises an event when we're running low on a particular ingredient. The bakery can use this notification to tell the Chef to go easy on that ingredient, while we stock our supplies.

  • Rhino Mocks


[Test]
public void Test_RaiseEventFromMock()
{
_mockChef.Expect(chef => chef.GoEasyOn("Sugar"));

_mockInventory.Raise(inv => inv.RunningLowOnIngredient += null,
this, new StockEventArgs("Sugar"));

_mockChef.VerifyAllExpectations();
}

To raise an event, invoke the Raise method on the mock with a null subscription to the event & the arguments to be passed onto the event handler method.
  • Moq


[Test]
public void Test_RaiseEventFromMock()
{
_mockChef.Setup(chef => chef.GoEasyOn("Sugar"));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null, new StockEventArgs("Sugar"));
_mockChef.VerifyAll();
}

Identical to Rhino except for the fact that you don't have to specify the 'sender' parameter.
  • jMock

Java doesn't support events as first-class citizens. You need to manually implement the publisher-subscriber pattern.

#9:Argument Constraints
Sometimes, we do not want to / cannot specify the exact arguments with which a method on a collaborator will be called as part of the expectation. In such cases, we use constraints on the arguments, which must be met for the expectation to be met.
e.g. from the previous example, lets say we don't know the value of the Low-stock-ingredient at compile-time. We have a variable into which we can fetch the ingredient and which we can use to compare against the actual value.
In short we want to specify a Predicate (a function which returns true/false) for an argument as a constraint.

  • Rhino Mocks


[Test]
public void Test_ConstrainingArguments()
{
var itemAboutToGoOutOfStock = "Eggs";
_mockChef.Expect(chef => chef.GoEasyOn(
Arg<string>.Matches (ingredient => ComplexCheck(itemAboutToGoOutOfStock, ingredient))));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null,
this, new StockEventArgs(itemAboutToGoOutOfStock));
_mockChef.VerifyAllExpectations();
}
private bool ComplexCheck(string expected, string actual)
{
return expected.Equals(actual); // any complex test
}

So here we use Arg.Matches(predicate) to do a complex constraint on the string argument for Chef#GoEasyOn(). There are a bunch of other helpful constraints - explore the Arg type docs (or the intellisense popup) for more.
  • Moq


[Test]
public void Test_ConstrainingArguments()
{
var itemAboutToGoOutOfStock = "Eggs";
_mockChef.Setup(chef => chef.GoEasyOn(
It.Is<string>(ingredient => ComplexCheck(itemAboutToGoOutOfStock, ingredient))));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null,
new StockEventArgs(itemAboutToGoOutOfStock));
_mockChef.VerifyAll();
}
private bool ComplexCheck(string expected, string actual)
{
return expected.Equals(actual); // any complex test
}

Moq has It.Is(predicate) for this purpose. Explore the type documentation (or the intellisense popup) for more helper constraints.
  • jMock

The example is different. Here we are constraining the arguments to the Bake call with a predicate.

//http://www.jmock.org/custom-matchers.html
@Test
public void test_expectAndCheckArgs()
{
context.checking( new Expectations() { {
oneOf(_mockInventory).isEmpty();
will(returnValue(false));
oneOf(_mockChef).bake(
with( FlavorMatcher.aPineappleFlavoredCake() ),
with( any(boolean.class)));
}} );
_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}


class FlavorMatcher extends TypeSafeMatcher<CakeFlavors>
{
public boolean matchesSafely(CakeFlavors flavor)
{ // any complex test

return flavor == CakeFlavors.Pineapple;

}
public void describeTo(org.hamcrest.Description description) {
description.appendText("a cake with pineapple flavor ");
}

@Factory
public static Matcher<CakeFlavors> aPineappleFlavoredCake()
{
return new FlavorMatcher();
}
}

once again more classes than I'd liked (Disclaimer: rusty java programmer could be the problem).

Use with(matcherInstance) in place of arguments in the expectation. Derive a new Matcher derived class with your custom check.


#9:Expect a sequence of calls in a specific order
Ordered Expectations: Looking at the test in Section#4 - the test can be satisfied by the following implementation

public void PleaseDonate(Order order)
{
_chef.Bake(order.Flavor, order.WithIcing);
var isEmpty = _inventory.IsEmpty;
}

which is not what we were getting at. Seems like the test is missing something... the order of calls! Chef.Bake should be called after Inventory.IsEmpty.
  • Rhino Mocks


[Test]
public void Test_ExpectCallsInOrder()
{
var mockCreator = new MockRepository();
_mockChef = mockCreator.DynamicMock<Chef>();
_mockInventory = mockCreator.DynamicMock<Inventory>();
mockCreator.ReplayAll(); // to avoid setting up an expect for an event handler subscribe in the following ctor.

_bakery = new Bakery(_mockChef, _mockInventory);

using (mockCreator.Ordered())
{
_mockInventory.Expect(inv => inv.IsEmpty).Return(false);
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false));
}

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockChef.VerifyAllExpectations();
_mockInventory.VerifyAllExpectations();
}


Woooaah! What just happened? Have a seat ; take a deep breath.
Ordered expectations have been a feature of Rhino Mocks; however the v3.5 syntax revamp hasn't made an impact here. This took some doing .. Turns out you need to go old-skool for a bit.
The key:
* Create a new MockRepository instance and invoke the DynamicMock method (instead of the static MockRepository.GenerateMock )
* Use the Ordered block to setup expectations in a specific order

  • Moq


[Test]
public void Test_ExpectCallsInOrder()
{
var sequence = String.Empty;
_mockInventory.Setup(inv => inv.IsEmpty).Returns(false)
.Callback(delegate { sequence += "1"; });
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Callback(delegate { sequence += "2"; });

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

Assert.AreEqual("12", sequence, "Calls not in expected order!");
_mockChef.VerifyAll();
_mockInventory.VerifyAll();
}

Last time I checked (Jan25,2010) Moq does not support this out of the box. However you could work around this with a collecting object. Very naive.. you could come up with better solutions to fit your exact context.
  • jMock


@Test
public void test_expectCallsInSpecificOrder()
{
final Sequence pleaseDonateSequence = context.sequence("pleaseDonate");
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
inSequence(pleaseDonateSequence);
will(returnValue(false));
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false);
inSequence(pleaseDonateSequence);
}});

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock has the shortest syntax for ordered expectations. You create a named Sequence object and then tag the name along with each expectation (listed in the expected order).

So there you have it. If it was a showdown, jMock would be ahead of Moq and Rhino Mocks would be just a sliver behind Moq.

JMock:
+ has a nice readable concise API for number of invocations and ordered expectations

Moq:
+ has a nice mechanism for type-safe custom callbacks and argument constraints

Rhino:
+ isn't bad. Does everything. However even with the v3.5 syntax revamp, it is a little unintuitive as compared to the others. The documentation was a bit noob-unfriendly, when I needed it. However it is the only option if can't use .net 3.5 for your tests (which should be rare).

Meet the frameworks : Rhino Mocks v Moq v jMock : Part 1

If you've been near any TDD-infected person, you're sure to have heard about Mock frameworks (or served as a by-standing casualty in a classicist v Mockist skirmish). Then you have to look. At first you're apprehensive, it looks like too much work (defining interfaces, creating mocks, expectations, et. all). Soon you're cornered by a Data Access object or a Network stream and you have no choice. You dip your feet into the pool of mocks.. soon enough you're splashing around like a silly kid creating mocks willy-nilly (they're free). Unknown to you, the pool has some whirlpools that suck you in when you're having too much fun and not paying any attention. In the end, it's like mock-Children of the Corn..

I'm a sucker for horror stories (and there's that other little matter of being biased towards state-based tests.) As with most things, there is more than one way to use a tool - mock frameworks are no exception. The folks at mockobjects.com have a new book out which explains the right way (not read it yet; maybe I'll still be converted into a mockist.)

Personally my pet-peeve with mock frameworks has been the learning curve. Usually you don't have a dedicated time-slot to learn a mock framework (and that's kind of a good constraint since the mock frameworks are flexible, powerful and consequently huge); I'd bet that most of us learn them while trying to get a test to pass. Nothing like a reluctant mock framework with cryptic error messages between you and a green bar, to get you into real-curse-practice. The only thing that comes a distant second is "Which is better? Rhino Mocks or Moq ?" from people who haven't explored either of them. If both of them scratch your itch, take a pick!

So I've tried to list down the most probable scenarios and try each of them with RhinoMocks, Moq and jMock (always wanted to write some tests in jUnit).

  1. Expect a Call on mockCollaborator.method()
  2. Expect a call on mockCollaborator.getProperty and return something
  3. Expect n calls to mockCollaborator.Method()
  4. Return values from mockCollaborator.Method()
  5. Expect no call (Don't call me!)
  6. Throw an exception in response to an expected call on mockCollaborator.Method()
  7. Custom callbacks or blocks of code to execute when a mockCollaborator.Method() is called
  8. Raise an event from a mock collaborator
  9. Argument Constraints
  10. Expect a sequence of calls in a specific order
You could use this to make your own choice (which is only yours to make). I've written this down as a self-reference for the next time I'm wondering "Why doesn't this @#&*(@ test fail?' or 'How is this test passing?'

A template for interaction-tests



For state-based tests, I'd usually write my assert first, step back to the action that will lead to the assert and finally arranging everything for the test to work. However this doesn't exactly work for interaction-based tests: In this realm, it's more helpful to write the action first, then the expectations and other steps for arrange and finally assert (which sometimes is just verifying that the expected mocks were called. Some frameworks like jMock do it automatically at the end of the test.)
Arrange
  1. create mock objects for collaborators that you want to mock( not Stub. I hope you've read Martin Fowler's paper [link] on the difference.)
  2. Create your test subject (here a Bakery type) and inject the mock collaborators via ctor/setter methods.
  3. Define the interaction via 'expects'. e.g. I expect the test subject to call methodX on collaboratorA with these parameters.
Act
  1. State the action/behavior that is the primary focus of this test
Assert
  1. Assert any state-change (if applicable)
  2. Verify all expected calls on the collaborators were called.


Source Code:
The source code for this series is available for browse/checkout (you'll need subversion to checkout) at
Dot Net code
Java code

#1: Expect a Call on mockCollaborator.method()
  • Rhino v3.5 (with NUnit 2.4.8)


Let's see how we do this in Rhino Mocks 3.5 - use the above section to work through this example.
Rhino mocks has changed with a (IMHO noob-friendly/simpler) syntax with version 3.5 - Prior to that an explicit record-replay style was the norm. So if you're using a prior version, try moving to v3.5. (There is a forsaken commented-out source file in the above mentioned link for old-skool Rhino).

To declare that you expect a method to be called, you use the Expect method on the respective mock object. Lambda expressions, Generics and type-inference result in compile-time checks and Intellisense guiding you all the way.
The below expectation reads "On the mockChef, expect Bake to be called with Vanilla and false as arguments." (when someone calls PlaceOrder() on the bakery, which employs the Chef)
I'm not going to post the code to make this pass inline (for honoring the memory of brevity in blog posts). I suggest you try TDDing your way through like me / refer to the source repository.



[Test]
public void Test_ExpectMethodCall()
{ // arrange : create mocks
var mockChef = MockRepository.GenerateMock<Chef>();

// arrange: inject dependencies
Bakery bakery = new Bakery(mockChef);
// arrange: expect the Bake method on Chef to be called
mockChef.Expect(chef => chef.Bake(CakeFlavors.Vanilla, false));

//act
bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Vanilla, WithIcing = false, Quantity = 1 });

//assert
mockChef.VerifyAllExpectations();
}
  • Moq v 2.0.5 (with NUnit 2.4.8)
Moq was the new kid on the block challenging the leading .Net mock frameworks with .Net3.5 lambda-expressions powered snappy syntax.



[Test]
public void Test_ExpectMethodCall()
{
//arrange
var mockChef = new Mock<Chef>();

//arrange: inject dep
var bakery = new Bakery(mockChef.Object);
// arrange: expect
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Vanilla, true));

//act
_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Vanilla, WithIcing = true, Quantity = 1 });
//assert
_mockChef.VerifyAll();
}

Differences
#1: mockChef.Object is the mock collaborator; this is a common stumble for people new to Moq. I think (unverified) this is due to Moq's design of not having a different Repository or Mockery type.
#2: Moq uses Setup for expecations (instead of Rhino's Expect)

  • jMock 2.5.1 (with jUnit 4.8.1)

jMock is the Java mock framework distilled from the experience of the gurus at mockobjects.com ; they have a new book out and are the recognized pioneers of the "Mock objects" technique. I highly recommend their second revision of the acclaimed 'Mock Roles not objects' paper.
So let's see how the test looks like in jMock:


Mockery context = new JUnit4Mockery();

@Test
public void test_expectCall()
{
Chef mockChef = context.mock(Chef.class);
Bakery bakery = new Bakery(mockChef);

context.checking( new Expectations() { {
oneOf(mockChef).bake(CakeFlavors.Pineapple, false );
} } );

bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 1) );
// mockChef.Verify() - autoverified : framework :)
}


Differences
#1: jMock has a more fluent approach to specifying expectations - look inside the Expectations creation. It reads 'Expect one invocation on mockChef of method bake with parameters Pineapple and false. Refer to the nicely written jMock cheatsheet in case you're feeling a bit lost.
#2: You don't need to explicitly verify expectations - automatically done at the end of a test case.


#2 Expect a call on mockCollaborator.getProperty and return something
I've factored out common code into a SetUp method to shorten the code snippets. In general, .Net properties = one get_property method + one set_property method + one backing field. Syntactic sugar!

So when someone queries Bakery.IsOpen, check to see if the Chef is available.

  • Rhino Mocks


[Test]
public void Test_ExpectPropertyGet()
{
_mockChef.Expect(chef => chef.IsAvailable).Return(true);
Assert.IsTrue(_bakery.IsOpen);

_mockChef.Expect(chef => chef.IsAvailable).Return(false);
Assert.IsFalse(_bakery.IsOpen);

_mockChef.VerifyAllExpectations();
}


Note the new Return method tagging along with the Expect to signify what should be returned when the Bakery makes a call to Chef#IsAvailable
  • Moq


[Test]
public void Test_ExpectPropertyGet()
{
_mockChef.Setup(chef => chef.IsAvailable).Returns(true);
Assert.IsTrue(_bakery.IsOpen);

_mockChef.Setup(chef => chef.IsAvailable).Returns(false);
Assert.IsFalse(_bakery.IsOpen);

_mockChef.VerifyAll();
}

Moq calls it Returns which IMHO reads better.
  • jMock

Java does not have properties as first class language features. They are manually implemented as accessor/mutator method pair and a backing field.

#3: Expect n calls to mockCollaborator.Method()
So if I place an Order for 3 Pineapple cakes, I'd expect the Chef#Bake to be called thrice.
  • Rhino Mocks


[Test]
public void Test_ExpectMultipleCalls()
{
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, true)).Repeat.Times(3);

_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Pineapple, WithIcing = true, Quantity = 3 });

_mockChef.VerifyAllExpectations();
}

Tag on the Repeat property to the Expect if you expect it to be called n times.
Caveat: the test fails if the mock isn't called at least 3 times. If you call it 3 or more times, the test passes. So if you have a need for exactly thrice, dive into the rhino mocks docs and let me know if you figure out a way to make it work.
  • Moq


[Test]
public void Test_ExpectMultipleMethodCalls()
{
_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Pineapple, WithIcing = false, Quantity = 3 });
_mockChef.Verify( chef => chef.Bake(CakeFlavors.Pineapple, false), Times.Exactly(3), "Chef should have been called thrice!");
}


Differences:
#1. With Moq, you specify this during verification with an overload of Verify (as opposed to while defining expectations)
#2 This test will pass only if Bake is called Exactly thrice (unlike Rhino)

  • jMock


@Test
public void test_expectMultipleCalls()
{
context.checking( new Expectations() {{
exactly(3).of(_mockChef).bake(CakeFlavors.Pineapple, false);
}} );

_bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 3) );
}

jMock wins this one for readabililty.
#4: Return values from mockCollaborator.Method()

Refer to #2 for Rhino and Moq. You tag on a Return/Returns method call to the expectation.
Let's say the bakery being a charitable organization, responds to a PleaseDonate message at the end of the day from cake-loving orphans. The bakery will ask the Chef to bake one for them after checking to see if they have surplus stocks in inventory.

  • jMock


@Test
public void test_expectCallAndReturnValue()
{
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
will(returnValue(false));
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false);
}} );

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock has a will method to signify what will happen when the method is invoked. Use the indentation (convention) so that it reads better.

#5:Expect no call (Don't call me!)
When the orphans send a PleaseDonate() and there are no surplus stocks in inventory, you wouldn't want to bother the overworked chef at the end of a weary day.
  • Rhino Mocks


[Test]
public void Test_ExpectNoCall()
{
_mockInventory.Expect(inv => inv.IsEmpty).Return(true);
_mockChef.Expect(chef => chef.Bake(Arg<CakeFlavors>.Is.Anything, Arg<bool>.Is.Anything))
.Repeat.Never();

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockInventory.VerifyAllExpectations();
_mockChef.VerifyAllExpectations();
}

Note: This snippet gives you a sneak peek of Argument Constraints. In short the second line states 'mockChef#Bake should not be called (irrespective of arguments)' Bring the .Repeat.Never() clause into plain view by placing it on a new line with one level of indentation.
  • Moq


[Test]
public void Test_ExpectNoCall()
{
_mockInventory.Setup(inventory => inventory.IsEmpty).Returns(true);
_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockChef.Verify(chef => chef.Bake(It.IsAny<CakeFlavors>(), It.IsAny<bool>()), Times.Never());
_mockInventory.VerifyAll();
}

Differences:
#1 Moq takes a different path of leaving the invocation-count check till the very end. Use the Verify Overload with Times.Never() as in Section#3
#2 Argument constaints in Moq read slightly better than Rhino.

  • jMock


@Test
public void test_expectNoCall()
{
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
will(returnValue(true));
never(_mockChef).bake( CakeFlavors.Pineapple, false );

}});

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock doesn't hide intent with never() leading the expectation. jMock's API shows the thought that's been put into it.

5 down. 5 for the next part.

My TDD Workshop

I was recently asked to conduct a workshop (read everyone-off-their-armchairs-and-type-with-me) on Test Driven Development. Now since this is something that I love (could not be any more apt for my 100th blog-post), I kind of "invested all of my self esteem in this presentation" as Dilbert would have said.

I don't have the code examples complete - I didn't like the way the GUI example turned out ; gonna give it another whirl soon.


Creative Commons License
Test driven development Workshop 2009 by Gishu Pillai is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Based on a work at docs.google.com.
Permissions beyond the scope of this license may be available at
my-tdd-workshop.html


My guiding principles were
  • to give the attendees a true taste of TDD (vs automated-tests after vs test-first programming)
  • to set up beacons to avoid the usual pits, which sink time, effort, people, projects
  • to condense what I felt were in the "must-know" category
  1. Test "driven" design - emergent design
  2. SOLID Principles
  3. Mocks and Dependency Injection
  4. Model View Presenter / Humble dialog way of building GUIs
  • to learn myself from the interaction (I've learned from a lot of people online. It 's only fair that I give back)
So I got onto google docs, fired up a presentation, wrote up a rough list of things that I considered important and off I went towards an initial draft. I asked around for a good non-toy problem for the code-alongs... to my surprise I didn't net that many.. so I settled for the Bowling Example of TDD yore (Ron Jeffries, Uncle Bob, et. all)
"Score a complete bowling game as per the standard scoring rules."

I also needed an extension to the problem that involved a bit of Mocks and GUIs (for some real world flavor) - so I extended the problem (of course with my "customer hat" on)
"Create a View/Display for the Bowling Game that shows pins rolled and score updates in real time."

I then tried to solve the problem myself. The second problem turned out to be more time-consuming than I imagined. (A definite possibility is that I had lost my touch with TDD and was rusty due to lack of practice - a shoutout to Naresh Jain, for helping me realize that)
Finally I published the draft online to the testdrivendevelopment yahoo group for scrutiny ; As always I got a lot of help and nice suggestions. (A big thank you! to all of you) I incorporated most of them - including expanding my 1-day plan to a 2-day (and finally a 3-day plan - Charlie Poole can go 'told you so')

I then conducted the first instance of the workshop with 13 attendees.
The first day went as per plan. TDD Origins, SOLID Principles, Bowling Game Part I.
However the second day, the rails came off. They loved the Rhino Mocks jumpstart - however coding along ate up a lot of hours. I skimmed the Moq equivalent exercise and somehow rushed through to the end. The grand-finale of building a GUI (which was supposed to illustrate how you can design incrementally and it's okay if you dont have a 30 page design-document blessed by the powers that be, if you pay attention to design all the time) had to be left as an "exercise for the attendee". I'll need to extend the workshop to a full 3 days next time.


Had the opportunity to do a lot of little experiments - like using a Chess Timer to time how much time I spent writing tests to code. Good fun overall! It also showed me that I need to tune my content a bit more - the anonymous feedback was encouraging. Scored a 100% on "Would you recommend this (session) to someone else" ? Just the impetus I needed to sink another bunch of hours tinkering with the content.

Testing .Net code with Cucumber and IronRuby

As promised, this is the culmination of this trilogy. The previous two posts were a jump-start on Cucumber to test Ruby code. Next I moved towards using Cucumber's plain text stories to test .Net code.Aslak Hellesoy has a wiki-post on how to do this ; however I found that you get eaten and spat out by a lot of IronRuby dragons along the way. So hold on..

1. Install the new DLR

First up install .Net Framework 4.0 (I have Beta1) - this has the new Dynamic Language Runtime (DLR) that makes things like IronRuby and IronPython possible.

2. Get the latest IronRuby release

Next we need to get IronRuby as a zip. Extract it to say d:\ironruby-0.9.0 Add the path to the bin folder to your PATH environment variable to avoiding lengthy paths. Drop to a command shell, type 'ir' to invoke the interactive IronRuby console. Type something simple to test if it works. It should.
>>>puts "Hello IronRuby"


3. Dragons ahead. Use diversion

But I hit a snag with this version of IronRuby, which had A BUG.

  • So I had to get the latest (8 Sep 2009 master to be precise) version of the source from the github repository to overcome that. You can download it as a zip or use git as you prefer. I got the zip
    ironruby-ironruby-90cdda82fd60f4b7e6d7d940501c586d55954466.zip (Could have used a shorter name)

  • Extract it to say d:\ir-src
    I hit a few path-too-long errors during extraction. Just keep skipping them. I think it's because of the rather large alphanumeric string which is the name of the top-level folder.

  • Once extracted, navigate to D:\ir-src\ironruby-ironruby-90cdda82fd60f4b7e6d7d940501c586d55954466\Merlin\Main\Languages\Ruby
    and open Ruby.sln in VS2008 (I have Dev Edition of VSTS.. Although it should build in VS Express Editions as per the docs - I couldn't get the solution to open in it.)
    Build Solution. At the end of it you should find the built binaries in
    D:\ir-src\ironruby-ironruby-90cdda82fd60f4b7e6d7d940501c586d55954466\Merlin\Main\bin\Debug

  • Rename that directory with the huge name to something like "ir".

  • Copy all built binaries and overwrite the ones from the 0.9.0 release's bin folder i.e. D:\ironruby-0.9.0\bin.


  • Open ir.exe.config in the same folder and update the Library paths element to the proper paths to folders within your ir-src folder. 'Handle with extreme care' or you'll lose hours chasing error messages. It should read
    Path#1 - D:\ir-src\ir\Merlin\Main\Languages\ (NOT D:\ir-src\ir\Merlin\External.LCA_RESTRICTED\Languages)
    Path#2 & #3 - D:\ir-src\ir\Merlin\External.LCA_RESTRICTED

    My xml looks like
    <set language="Ruby" option="LibraryPaths" 
    value="D:\ir-src\ir\Merlin\Main\Languages\Ruby\libs\;D:\ir-src\ir\Merlin\External.LCA_RESTRICTED
    \Languages\Ruby\redist-libs\ruby\site_ruby\1.8\;D:\ir-src\ir\Merlin\External.LCA_RESTRICTED\Lang
    uages\Ruby\redist-libs\ruby\1.8\" />




4. Wrapper script ICucumber

Lastly we need a wrapper script to invoke cucumber with Ironruby. Create a file called icucumber.bat under your Ruby bin folder i.e. D:\Ruby\bin\icucumber.bat with the following text.

REM Update with appropriate values for GEM_PATH, Ruby bin and the path to ir.exe
@ECHO OFF
REM This is to tell IronRuby where to find gems.
SET GEM_PATH=d:\ruby\lib\ruby\gems\1.8
"D:\ironruby-0.9.0\bin\ir.exe" -D -X:ExceptionDetail "d:\ruby\bin\cucumber" %*


5. Back to our example from the previous two posts.
The .feature file stays unchanged.
Delete c:\cukes\dot_net_features\support\BowlingGame.rb ; since we're going to implement the same in C# this time around as
c:\cukes\dot_net_features\support\BowlingGame.cs




namespace CukesDemo
{
public class BowlingGame
{
public void roll(int pins_knocked_down)
{
Score += pins_knocked_down;
}

public int Score
{
get; set;
}
public bool Over
{
get { return false; }
}
}
}


Also create a small batch file to compile it to a DLL (Assumes csharp compiler is on the PATH).
c:\cukes\dot_net_features\support\Compile.bat

IF EXIST bin GOTO COMPILE
MKDIR bin
:COMPILE
csc /t:library /out:bin/BowlingGame.dll bowling_game.cs


Finally back to our step definitions to check the glue. Four changes needed - explained in comments.
cukes\dot_net_features\step_definitions\bowling_game_steps.rb


# CHANGE 1 : Add bin folder to load-path
$:.unshift(File.dirname(__FILE__) + '/../support/bin')
# CHANGE 2 : Get BowlingGame.dll
require 'BowlingGame'

Given /^I am starting a new game$/ do
# CHANGE 3 : Use Namespace::ClassName.new
@game = CukesDemo::BowlingGame.new
end

When /^I roll (\d+) gutter balls$/ do |count|
count.to_i.times{
@game.roll(0)
}
end

Then /^the score should be (\d+)$/ do |expected_score|
@game.score.should == expected_score.to_i
end

Then /^the game should be over$/ do
# CHANGE 4 : be_over passes even if Over returns false. Don't know what is the equiv of over?

in .Net
#~ @game.should be_over == true
@game.over.should == true
end

When /^my rolls are (.*)$/ do |rolls|
rolls.split(' ').each{|roll|
@game.roll(roll.to_i)
}
end


Now for the grand finale, run Cucumber to verify our .Net DLL via IronRuby !!!
[Cukes_06.jpg]

HTH