Domain name change

From now on, new posts will be published on usingimho.wordpress.com



Unit testing with Ruby (part 2)

In ruby, you can do this:

Class methods mocking

Class methods mocking

Hum. Static’s bad, don’t do static, mkay? Well, not necessarily. The fact that you can test class methods like this makes them much more usable than they are in C#, where using static all over the place brings your design to the dumpster pretty quickly. Still, the use of class methods usually covers for underlying design flaws, so it’s a technical debt and you should evaulate what is convenient to do case by case.

The above snippet is powered by mocha, a mocking framework for ruby. It has a JMock-like syntax and it provides you all the usual tools.


creates a mock object. You can set expectations on a mock object with


and stubs with


Expectations are verified at the end of the test: if you’ve set an expectation for :method_name and that method isn’t called on the mock object before the end of the test, that test will fail (no need to VerifyAllExpectations or such). Instead, stubs do not fail the test if not called.
So, in the following example:

if we remove the object.second call from the method run only the second test fill fail.

As seen before, you can set expectations and stubs not just on mocks but on any object, even class objects. Abusing of this feature, as to say in object = Object.new; object.expects(:method) ,  is probably not wise but as shown in the first snippet this allows testing of usually not testable situations.

You can force constraints on expectations using with(param_value) and you can return values with returns(value). For example, the following code:

mock_object = mock()

Sets an expectation on mock_object for the method get_capital, the expectation is satisfied only if get_capital is called with the string 'sweden' and, if called that way, returns the string 'stockholm'. Of course you don’t need both clauses to be present togheter, mock_object.expects(:get_capital).with('sweden') and mock_object.expects(:get_capital).returns('stockholm') work just as expected. If you don’t set a return value for any given expectation/stub it will return nil.

stub_everything() returns a mock object that stubs every possible method call. The return value will always be nil.

More on mocha will be found on its documentation page.


Is C better than Ruby?

Yesterday I stumbled into this through hacker news and well, maybe the guy hasn’t really grasped the whole client-server paradigm thing but here he really made a point :

We’re engineers, and we make machines work. You use the best tool for the job to do that. You don’t choose some pretty language [Ruby] that “brings back the joy of coding” or equivalent hippy shit.

And more:

C is the dominant language right now and probably for the distant future. It’s the lingua franca of computing. Nearly every server application worth a damn is written in C.

Well, the guy here maybe needs to chill out a bit but I think he’s right: C is here to stay. Planning to use anything else for a large project where performance is crucial is insane (Java and C#, you heard me :-)). C is a really powerful and valuable tool, and every developer should have at least some knowledge of it: I started out with C64 Basic, then Assembly for a long, long time, then lots of C, after that Java, VB, C# and then Ruby. I know people like Why are promoting Ruby as a learning language but honestly, I can’t really imagine someone with no knowledge of C writing good Ruby.

But probably in the 70’s somebody made similar statements, just replacing C with FORTRAN. Right now, C is the language. What about it in 10 years? I’m really, really surprised every time I read such statements: they make me feel like story never happened. No wonder Berlusconi is gonna win the elections with 70% of the votes next week.

And even if C is the best all-purpose tool we have now, what’s the point in using it even if the situation would allow a not-so performant but much more pleasant to use tool instead? Is there some kind of pride to gain in being miserable doing your job that I’m not seeing? Ruby performs like crap, but it’s a pleasure to work with. And 99% of the times nobody cares about performance.

All these things have been said countless times by people way more authoritative than I will ever be but it seems there’s still need to state them clear…


Castle windsor oddities

I was at a customer today and they had a quite interesting situation to show me, and here it is.

Let’s create these dummy entities:



And now let’s register them the same way they did and see what happens when trying to resolve a Person:


As you can see Windsor actually “resolves” both Address and Job as if they were a dependency, setting both of them as a new instance! I don’t really think this is a bug but it’s totally not what I expected…

Having interfaces in between (so IPerson, IAddress and IJob) and then trying to resolve IPerson solves the “problem” (so I get a person with null Address and Job).


Unit testing with Ruby (part 1)

Not having the compiler on your side makes life difficult. Example:


public int Multiply(int firstFactor,int secondFactor)
      return firstFactor*secondFactor;


def multiply(first_factor, second_factor)
   return first_factor*second_factor

What these methods are supposed to do is pretty straightforward. What they actually do, maybe not so.  What if you were to test both methods? What\how many tests would you write to make sure these methods behave as you expect?

Let’s take a look at the C# method. It takes two parameters (both int, so value types) and returns an integer. Relying on cyclomatic complexity to determine, for a given method, how many tests must be written is often uncorrect but let’s assume that it’s okay for this case, so one test that verifies the result for a given input might be enough.

What about the Ruby method? It takes two parameters and returns something. And the two parameters might be pretty much anything. How about testing this one? There’s no IFs so we might say that one test is still fine, or you might want to check parameters for correctness, or maybe make sure that who calls your method do it the way it’s supposed to. Either options (except the first but seriously, you’re not going for that one) requires extra effort in comparison to the C# approach.

About mocking:


public Controller(IView view, IModel model)
      //some stuff happening here

And Ruby

def initialize(view, model)
      #some stuff happening here

Mocking view and model in C# requires some degree of IView = repo.CreateMock<IView>(). This relies on the IView interface, and you’ve got nothing like that in Ruby. You just mock methods instead. Mocha syntax:

def test_refresh_always_callRefreshOnView
   view = Mock()
   controller = Controller.new(view,Stub())

No need of VerifyAllExpectations() or such: this fails automatically if refresh is not invoked on the view object.

A similar problem arises when using IoC containers: you’ve got no interface to resolve. More about this later.


Color scheme designer

I’m an engineer: I can see up to 16 colors and I normally use 4 plus black and white, I’ve got a shortcut for terminal, I use that often and come on, what the f*ck is MistyRose supposed to be.  Still, or maybe especially for those reasons, I found this to be very interesting and i suggest you to give it a look: it is for me what VBA macros are to the average programming noob🙂


Interface designing with Ruby and GTK+

As I said some posts ago, there is no support for GUI building with Ruby inside NetBeans or any other Ruby IDE (with the exception of Komodo). That means you’ll have to rely on external tools, namely the Qt Designer or the Glade interface designer (for GTK+): they are plentiful in features, really easy to use and documentation is widely available so it will be not a problem for you to create good GUIs with them in no time. The only problem about using one of these tools instead of building your GUI with your favourite IDE is that you’ll have to integrate your interface (externally built) with the code you’re writing. Let’s see how, using Glade and GTK+.

After creating a new Glade project some windows will pop up. Among them will be the palette window and the properties window : the first one allows you to create new widget, so click on the upper left button to create a window widget, then add a button to the newly created window by selecting the button widget and then left-click on the window body.

Palette window

Palette window

Now it’s time to look at the property window. By selecting the button that you craeted the property window will show all its properties. Select the signals tab and then click on the ellipse on the lower left of the window: that will show a dialog containing all the button’s available signals. Double click on clicked, then click add on the signals window.

Signals window

Signals window

Now save the project and close the Glade designer. You will see that Glade created two files in the folder you chose: the one that cares to us it the yourprojectname.glade file. Now open a terminal at the folder location and type in:

ruby-glade-create-template yourprojectname.glade > yourrubyfile.rb

Where yourrubyfile is a filename of your choice. This will create a new yourrubyfile.rb that looks like:

#!/usr/bin/env ruby
# This file is gererated by ruby-glade-create-template 1.1.4.
require 'libglade2'

class yourrubyfileGlade
  include GetText

  attr :glade

  def initialize(path_or_data, root = nil, domain = nil, localedir = nil, flag = GladeXML::FILE)
    bindtextdomain(domain, localedir, nil, "UTF-8")
    @glade = GladeXML.new(path_or_data, root, domain, localedir, flag) {|handler| method(handler)}


  def on_button1_clicked(widget)
    puts "on_button1_clicked() is not implemented yet."

# Main program
if __FILE__ == $0
  # Set values as your own application.
  PROG_PATH = "yourprojectname.glade"
  Project1Glade.new(PROG_PATH, nil, PROG_NAME)

Running the file will display the window you created and clicking on the button will execute whatever logic you’ve put inside the on_button1_clicked method.