tags:

views:

60

answers:

1

I am trying to verify if a text have been written to file (build.log) after executing a rake task which will throw an exception. Checkout both the code snippets below, the one with begin works whereas lambda throws a message saying it couldn't find the build.log file.

Using begin to test.(works)

  begin 
     Rake::Task['git:checkout'].invoke //writes "destination already exists" to build.log
  rescue
  end
  IO.read(@project_folder+@build_id+"/build.log").should match(/.*destination.*already.*exists.* /)   

Trying to test the same using lambda. (Not works)

  lambda {
    Rake::Task['git:checkout'].invoke //writes "destination already exists" to build.log
  }
  IO.read(@project_folder+@build_id+"/build.log").should match(/.*destination.*already.*exists.* /) 

What is the difference between these two?

+4  A: 

You're thinking of lambda incorrectly. A lambda is a suspension of runnable code. I say suspended, because it's ready to run, even ready to take arguments, but it hasn't actually done anything yet.

For example, consider the following (passing) spec:

flag = false
x = lambda {            # Here, we suspend a function to set our flag.
  flag = true
}

flag.should == false    # The code in the lambda is still suspended;
                        # it hasn't done any work.

x.call                  # Now we ran the suspended function.
flag.should == true

Notice two things:

  1. I got an object out of the lambda keyword. You're getting this object, too, but since you don't assign it to a variable it's immediately lost. ;)
  2. I used the call method to actually execute the code in the suspension (i.e. in the lambda). In your given example, you aren't actually running your git:checkout task at all!

begin ... rescue ... end is a completely different mechanism: the purpose is to correctly handle (or in your case, to swallow) exceptions. Stick with this form; it's the only one that does what you need. :)

Andres Jaan Tack
Thanks very much. Your answer clarified my confusion.
Muthu