[rspec-users] Testing methods that yields a block

Chris Flipse cflipse at gmail.com
Tue Oct 12 12:18:10 EDT 2010


On Thu, Oct 7, 2010 at 10:24 AM, ignacy.moryc <imoryc at gmail.com> wrote:

> 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.
>
>
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 ...)


> Is there a better way to test this method?
>
> Thanks,
>
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>



-- 
// anything worth taking seriously is worth making fun of
// http://blog.devcaffeine.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20101012/830e0174/attachment.html>


More information about the rspec-users mailing list