# Mocking a method with a block

**URL:** <https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496>\
**Category:** Ruby\
**Created:** [July 31, 2010, 5:38pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496 "2010-07-31T17:38:47Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [July 31, 2010, 5:38pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/1 "2010-07-31T17:38:47Z")

</div>

Hi people,

I have an application that download emails from an email account an  
process them.

What I would like to do is to mock the mail download petition and not  
process the real mails but an array of mails I have for this propos.

This is the precise situation: I have this:

```auto
      Net::POP3.start( opts[:server], port, opts[:user], opts[:pass] )
do |pop|
        pop.each_mail do |m|
          block.call( m )
        end
      end
```

I would like to have a mock that if on my test call to

=\> Net::POP3.start( opts[:server], port, opts[:user], opts[:pass] ) do  
|pop|

Not any mailing petition is done but the body of the method is still  
working but not with real mails but with an array of fake mails like  
this:

=\> mails = [ File.read(’/dir/mail1.raw\_mail’),  
File.read(’/dir/mail2.raw\_mail’)]

Is this possible?.. am I completely lost?.. is there any better way to  
do this?

Any suggestion is welcome.

Thanks

f.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 1, 2010, 1:10am UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/2 "2010-08-01T01:10:32Z")

</div>

On Sat, Jul 31, 2010 at 5:38 PM, Fernando G.  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> [code]  
> =\> Net::POP3.start( opts[:server], port, opts[:user], opts[:pass] ) do  
> do this?  
> One option would be to change the start method of Net::POP3 to do  
> exactly what you describe.  
> Remember that Ruby is open and you can redefine any method on any  
> class. You can always alias the method start before changing it, so  
> you can revert to the original definition after the test.

Jesus.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 1, 2010, 10:40am UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/3 "2010-08-01T10:40:03Z")

</div>

JesÃºs Gabriel y GalÃ¡n wrote:

> One option would be to change the start method of Net::POP3 to do  
> exactly what you describe

This is a good idea.

I can open the class Net::POP3 and redefine the method .start.

Now, how can I organize this to charge the redefinition of the method at  
the beginning of the test and revert it at the end of the test.

I mean, if I have a file that redefine the Net::POP3.start method I can  
‘require’ it but I don’t know how to ‘un-require’ it.

Also I would like to simulate that the Net::POP3.start charges my mails  
array (different on every test) and if I redefine this method in a  
generic way I don’t know how to use my mails array inside the redefined  
method.

Example, if I have my own redefinition of the method like:

```auto
    class Net::POP3
      def self.start( *, &block )

         (How can I put my mails array in here?)

      end
    end
```

I think I need some kind of mocking tutorial or something, if you know  
any one and you can offer me the link it will be great.

Thanks

f.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 8:21am UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/4 "2010-08-02T08:21:44Z")

</div>

On Sun, Aug 1, 2010 at 10:40 AM, Fernando G.  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Jesús Gabriel y Galán wrote:
> 
> > One option would be to change the start method of Net::POP3 to do  
> > exactly what you describe
> 
> This is a good idea.
> 
> I can open the class Net::POP3 and redefine the method .start.
> 
> Now, how can I organize this to charge the redefinition of the method at  
> the beginning of the test and revert it at the end of the test.

You can use alias\_method to “save” a copy of the original method with  
another name. You can do this in the setup of your tests, and revert  
back to that version in the teardown:

irb(main):001:0\> class A  
irb(main):002:1\> def self.test  
irb(main):003:2\> “original test”  
irb(main):004:2\> end  
irb(main):005:1\> end

irb(main):013:0\> class A  
irb(main):014:1\> class \<\< self  
irb(main):015:2\> alias\_method :orig\_test, :test  
irb(main):016:2\> end  
irb(main):017:1\> end

# at this point you can call A.test and A.orig\_test and both do the same

# now you can create a new version of the method:

irb(main):020:0\> class A  
irb(main):021:1\> def self.test  
irb(main):022:2\> “new test, original was [#{orig\_test}]”  
irb(main):023:2\> end  
irb(main):024:1\> end  
=\> nil  
irb(main):025:0\> A.test  
=\> “new test, original was [original test]”  
irb(main):026:0\> A.orig\_test  
=\> “original test”

As you can see, you can still refer to the original method. To put it  
back:

irb(main):027:0\> class A  
irb(main):028:1\> class \<\< self  
irb(main):029:2\> alias\_method :test, :orig\_test  
irb(main):030:2\> end  
irb(main):031:1\> end  
=\> #Class:A  
irb(main):032:0\> A.test  
=\> “original test”

(this leaves the orig\_test method around, but I don’t think that would  
be a problem).

> I mean, if I have a file that redefine the Net::POP3.start method I can  
> ‘require’ it but I don’t know how to ‘un-require’ it.
> 
> Also I would like to simulate that the Net::POP3.start charges my mails  
> array (different on every test) and if I redefine this method in a  
> generic way I don’t know how to use my mails array inside the redefined  
> method.

If this is just for running a test you could use a global variable or  
a constant:

irb(main):034:0\> MY\_EMAILS = %w{a b c d e}  
=\> [“a”, “b”, “c”, “d”, “e”]  
irb(main):035:0\> class A  
irb(main):036:1\> class \<\< self  
irb(main):037:2\> alias\_method :orig\_test, :test  
irb(main):038:2\> def test  
irb(main):039:3\> “my emails: #{MY\_EMAILS}”  
irb(main):040:3\> end  
irb(main):041:2\> end  
irb(main):042:1\> end  
=\> nil  
irb(main):043:0\> A.test  
=\> “my emails: abcde”

You can also look at class\_eval and define\_method to build a closure  
around your emails’ variable (sorry, don’t have time now to do that,  
I’ll come back later if you need it).

Jesus.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 3:53pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/5 "2010-08-02T15:53:33Z")

</div>

Fernando G. wrote:

> Is this possible?.. am I completely lost?.. is there any better way to  
> do this?

I’d suggest you use an existing mocking library like “mocha”. Example:

-------- 8\< ----------------  
require ‘net/pop’  
require ‘test/unit’  
require ‘rubygems’  
require ‘mocha’

# code to test

class Foo  
attr\_reader :opts  
def initialize(opts)  
@opts = opts  
end  
def bar(block)  
Net::POP3.start( opts[:server], opts[:port], opts[:user],  
opts[:pass] ) do |pop|  
pop.each\_mail do |m|  
block.call( m )  
end  
end  
end  
end

# tests

class MyTest \< Test::Unit::TestCase  
def test\_1  
mails = [“xxxxx”,“yyy”]  
mockpop = mock  
mockpop.expects(:each\_mail).multiple\_yields(\*mails)  
Net::POP3.expects(:start).with(“127.0.0.1”, 110, “a”,  
“b”).yields(mockpop)

```
foo = Foo.new(:server=>"127.0.0.1", :port=>110, :user=>"a", 

```

:pass=\>“b”)  
res =   
foo.bar(lambda { |x| res \<\< x.size })  
assert\_equal [5,3], res  
end

# more expectation-based style

def test\_2  
mails = [“xxxxx”,“yyy”]  
mockpop = mock  
mockpop.expects(:each\_mail).multiple\_yields(\*mails)  
Net::POP3.expects(:start).with(“127.0.0.1”, 110, “a”,  
“b”).yields(mockpop)

```
mockblock = mock
seq = sequence(:block)
mockblock.expects(:call).with(mails[0]).in_sequence(seq)
mockblock.expects(:call).with(mails[1]).in_sequence(seq)

foo = Foo.new(:server=>"127.0.0.1", :port=>110, :user=>"a", 

```

:pass=\>“b”)  
foo.bar(mockblock)  
end  
end  
-------- 8\< ----------------

I find there’s something unsatisfying about tests which look like this.  
Sometimes you can spend more effort on the mechanics of mocking than on  
solving the original problem, and the resulting tests are closely  
coupled to the internal implementation of your function. But that _is_  
what you asked for 🙂

Refactoring might make your code easier to test. e.g.

-------- 8\< ----------------  
require ‘net/pop’  
require ‘test/unit’  
require ‘rubygems’  
require ‘mocha’

class Foo  
attr\_reader :opts  
def initialize(opts)  
@opts = opts  
end  
def bar(block)  
for\_all\_messages do |m|  
block.call(m)  
end  
end  
private  
def for\_all\_messages(&blk)  
Net::POP3.start( opts[:server], opts[:port], opts[:user],  
opts[:pass] ) do |pop|  
pop.each\_mail(&blk)  
end  
end  
end

class MyTest \< Test::Unit::TestCase  
def test\_1  
foo = Foo.new({})

```
mails = ["xxxxx","yyy"]
foo.expects(:for_all_messages).multiple_yields(*mails)
res = []
foo.bar(lambda { |x| res << x.size })
assert_equal [5,3], res

```

end  
end  
-------- 8\< ----------------

HTH,

Brian.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 4:12pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/6 "2010-08-02T16:12:24Z")

</div>

Brian C. wrote:

> Fernando G. wrote:
> 
> > Is this possible?.. am I completely lost?.. is there any better way to  
> > do this?
> 
> I’d suggest you use an existing mocking library like “mocha”.

This was how I started to try mock the Net::POP3.

But instead of using the .yields method, that I didn’t know about, I  
tried to mock directly the Net::POP3.start method and this didn’t work.

Thanks a lot for your comprehensive examples and also for the  
re-factoring suggestion for an easier mock.

Best regards.

f.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 4:31pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/7 "2010-08-02T16:31:14Z")

</div>

Fernando G. wrote:

> But instead of using the .yields method, that I didn’t know about, I  
> tried to mock directly the Net::POP3.start method and this didn’t work.

It would be really useful if you could attach arbitrary behaviour to a  
mocked method - perhaps ‘returns’ with a block:

m = [1,2,3]  
Net::POP3.expects(:start).returns { m.each { puts m }; m.size }

This is something I’ve missed badly in the past, and I’ve ended up  
mocking directly using Object.new and defining singleton methods.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 6:22pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/8 "2010-08-02T18:22:45Z")

</div>

Hi again people,

Following your suggestions I am trying to build an small library to  
abstract this behavior on a reusable way:

- [http://github.com/fguillen/NetPopMock](http://github.com/fguillen/NetPopMock)

My problem now is that I’m not able to use the _raw\_mails_ array sent on  
the **NetPopMock.fake** call

See the test example:

- 

[http://github.com/fguillen/NetPopMock/blob/master/test/net\_pop\_mock\_test.rb#L15](http://github.com/fguillen/NetPopMock/blob/master/test/net_pop_mock_test.rb#L15)

Into the mocked class:

- [http://github.com/fguillen/NetPopMock/blob/master/net\_pop\_mock.rb#L30](http://github.com/fguillen/NetPopMock/blob/master/net_pop_mock.rb#L30)

Jesus was the first one suggesting me to use _class\_eval_ and I told him  
that I thought I was enough information to work on my self… well that  
was not true… I need help again 🙂

I know the solution is in a mix of _eval_ and _binding_ but I don’t find  
it.

Thanks again

f.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 8:28am UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/9 "2010-08-02T08:28:34Z")

</div>

JesÃºs, Thank you so much for your help.

I think I have enough information to work by my self.

Thanks for your work.

f.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 6:27pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/10 "2010-08-02T18:27:37Z")

</div>

Thinking I found the solution:

- 

[http://github.com/fguillen/NetPopMock/commit/7003aa7db33f98165a10987058ece171a7b371dd](http://github.com/fguillen/NetPopMock/commit/7003aa7db33f98165a10987058ece171a7b371dd)

Do you think is a clean solution?

Regards

f.

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 6:30pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/11 "2010-08-02T18:30:51Z")

</div>

Fernando G. wrote:

> See the test example:
> 
> - 
> 
> [http://github.com/fguillen/NetPopMock/blob/master/test/net\_pop\_mock\_test.rb#L15](http://github.com/fguillen/NetPopMock/blob/master/test/net_pop_mock_test.rb#L15)
> 
> Into the mocked class:
> 
> - [http://github.com/fguillen/NetPopMock/blob/master/net\_pop\_mock.rb#L30](http://github.com/fguillen/NetPopMock/blob/master/net_pop_mock.rb#L30)

Sorry the links are not static, use this others:

- 

[http://github.com/fguillen/NetPopMock/blob/db7d3dae0ce091cc870ef23cce7487ee44c2b927/test/net\_pop\_mock\_test.rb#L15](http://github.com/fguillen/NetPopMock/blob/db7d3dae0ce091cc870ef23cce7487ee44c2b927/test/net_pop_mock_test.rb#L15)

- 

[http://github.com/fguillen/NetPopMock/blob/db7d3dae0ce091cc870ef23cce7487ee44c2b927/net\_pop\_mock.rb#L30](http://github.com/fguillen/NetPopMock/blob/db7d3dae0ce091cc870ef23cce7487ee44c2b927/net_pop_mock.rb#L30)

---

<div class="post-metadata">

**Author:** ![fearx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/82dd89/32.png) [@fearx](https://www.ruby-forum.com/u/fearx)\
**Post date:** [August 2, 2010, 7:57pm UTC](https://www.ruby-forum.com/t/mocking-a-method-with-a-block/192496/12 "2010-08-02T19:57:56Z")

</div>

The history just finished with this:

- [fibber\_mailman | RubyGems.org | your community gem host](http://rubygems.org/gems/fibber_mailman)

Any suggestion or comment will be welcome.

Thanks again

f.
