# How to test an iterator method

**URL:** <https://www.ruby-forum.com/t/how-to-test-an-iterator-method/180667>\
**Category:** Ruby\
**Created:** [December 25, 2009, 4:28pm UTC](https://www.ruby-forum.com/t/how-to-test-an-iterator-method/180667 "2009-12-25T16:28:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Edgardo\_H](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/c68b51/32.png) [@Edgardo\_H](https://www.ruby-forum.com/u/Edgardo_H)\
**Post date:** [December 25, 2009, 4:28pm UTC](https://www.ruby-forum.com/t/how-to-test-an-iterator-method/180667/1 "2009-12-25T16:28:27Z")

</div>

Hi guys,

I have a class that looks like this

class MyClass  
def each\_object  
# do something really fun  
end  
end

I’d like to write some tests for the #each\_object method but don’t  
know how to. Could you please suggest a way to test methods that  
iterate over the elements of a collection?

Thanks,  
Edgardo

---

<div class="post-metadata">

**Author:** ![Edgardo\_H](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/c68b51/32.png) [@Edgardo\_H](https://www.ruby-forum.com/u/Edgardo_H)\
**Post date:** [December 25, 2009, 5:22pm UTC](https://www.ruby-forum.com/t/how-to-test-an-iterator-method/180667/2 "2009-12-25T17:22:35Z")

</div>

On 12/24/2009 01:14 AM, Edgardo H. wrote:

> I’d like to write some tests for the #each\_object method but don’t  
> know how to. Could you please suggest a way to test methods that  
> iterate over the elements of a collection?

Depends on what you want to check. If for example you want to make sure  
elements are returned in the proper order you can do something like  
this:

class X  
include Test::Unit::Assertions

def test\_a  
v = 1…5  
expect = [1,2,3,4,5]

```
 v.each do |x|
   assert_equal expect.shift, x
 end

```

end  
end

This is of course just a silly test but should demonstrate the point.

Kind regards

robert
