RSpec Impression

As a novice Ruby programmer, I still dont understand a lot of things. However I have to admit Ruby is really flexible. Ruby has a lot of usable libraries which are distributed by RubyGems package manager, hence the library format is called gem. It is comparable to NuGet in .NET and npm for Node.js.

One of the several libraries that impressed me is RSpec, which is a BDD library. It has similarities with Mocha and its addons (like should.js) in JavaScript world, however Ruby language construct allows more flexibilities. I like the way the expectation construct works:

actual.should be >= expected

actual.should =~ /regex/

expect { my_class.process() }.to raise_error(ErrorClass)

Stubbing method is also quite easy, even for ActiveRecord classes. Assume that Student is ActiveRecord class, we can do it directly like this

Student.stub(:find){fake_students}

If we use Entity Framework / other ORMs in C# we will need another layer to make it easier for testing. It is more of limitation of C# as static typed language.

Checking whether a method is triggered is also simple. We will use this dummy scenario where Agent instance will raise exception if its id is invalid.

class Validator
    def validate(input)
        true
    end
end

class Agent
    attr_accessor :code, :validator

    def initialize(args = nil)
        if args
            args.each do |k,v|
                instance_variable_set("@#{k}", v) unless v.nil?
            end
        end
    end

    def check_state
        state = self.validator.validate(self.code)
        raise "Invalid" unless state
    end
end

describe Agent do
    describe "#check_state" do
        it "should raise error if code is invalid" do
            validator = double('validator')
            code = "008"
            agent = Agent.new(:code => code, :validator => validator)
            validator.should_receive(:validate).with(code).and_return(false)
            expect {agent.check_state}.to raise_error
        end
    end
end

An expert programmer once said to me “if all you have is a hammer, everything looks like a nail".

Well now I have much more respect for Ruby and Python, but it doesn’t change the fact that C# is a better language.