Powered By BlogNow - Get Your Free Blog

I have moved!

My new blog is at lindsaar.net

All the old content will stay here though. But check out the new blog

¿ 25/7/2007 - How to mock a block?

I guess you could just call it dull witted.... but while it might achieve the goal of mocking the block... it wouldn't get your spec passed. And probably is not the Ruby Way.

So, I had to dig and look and hunt and scratch.

After a lot of that, I didn't find the answer....

SO!  I went on the RSpec mailing list and asked, and lo and behold, an answer cometh...

Here is the situation (so you guys can avoid the same problem).

Basically, I wanted to do a look up of the MX record against a domain name to work out if that domain name is a valid address to receive email or not.

Using the Resolv library, I was calling a class method which returned another class instance which then had another class method called on it to get a result.  Complicated?  Only in writing, this is what I was doing:

  Resolv::DNS.open do |dns|
    @mx = dns.getresources(domain_name, Resolv::DNS::Resource::IN::MX)
  end


What I wanted to do is control, in my spec, what value was assigned to @mx.

The solution?  Insanely simple (as most ruby is, just call "and_yields" instead of "and_returns".  So my spec now looks like this:

 @dns = mock(Resolv::DNS)
 Resolv::DNS.should_receive(:open).once.and_yield(@dns)


I hope that helps some other people out there.
Of course, that is only the snippet of the spec, only what you need to get started :)

blogLater

Mikel
Post A Comment! :: Send to a Friend!

About Me

AKA Raasdnil, this site is about web coding, hosting and all other matters that relate to this... especially Ruby on Rails!

Links