Testing methods that yields a block

I want to test a class method that sets some state and then yields a
block. It looks something like that:

class Cat
class << self
def start
id = get_uuid
begin
yield if block_given?
ensure
set_some_other_state
end
end
end
#…
end

How can I test that id field was set? Or that set_some_other_state
method was called, if I intend to use this class like this:

Cat.start do

do what cat’s do

end

I’m trying to do this like this:

Cat.start { #some block }
Cat.id.should be_something

but this doesn’t work.

I also used:

Cat.should_receive(:id=).once
Cat.start {#some block}

but this doesn’t let me see to what the id field was set.

Is there a better way to test this method?

Thanks,

On Thu, Oct 7, 2010 at 9:24 AM, ignacy.moryc [email protected] wrote:

   set_some_other_state

do what cat’s do

end

I’m trying to do this like this:

Cat.start { #some block }
Cat.id.should be_something

but this doesn’t work.

What do you mean “doesn’t work”? Are you getting a failure message?
What does it say?

On Thu, Oct 7, 2010 at 10:24 AM, ignacy.moryc [email protected] wrote:

          set_some_other_state

do what cat’s do

Cat.should_receive(:id=).once
Cat.start {#some block}

but this doesn’t let me see to what the id field was set.

I think you’re seeing a legitimate failure … You’re tripping up
against a
scoping problem in the line where you set the id. You’re setting a
local
variable “id” to the value, which falls out of scope by the time your
spec
is verifying anything.

You’ll need something more like:
self.id = get_uuid
(and possibly an attr_accessor definition for :id as well …)

end
#…
end

In spite of the fact that you have an #id= method, id = get_uuid is
setting a local variable, not invoking the #id= method. Use self.id = get_uuid to invoke the method and set the attribute.

Myron