What does duck_type(:each) mean ?

66 views
Skip to first unread message

Arup Rakshit

unread,
Jul 9, 2014, 4:41:40 AM7/9/14
to rs...@googlegroups.com
Hi,


I found 

with(duck_type(:each)) will match call like this - foo([])

But the same can be done also

with(instance_of(Array)) ->  foo([])

What is the difference between these 2 ?

Regards,
Arup Rakshit

Sam Phippen

unread,
Jul 9, 2014, 4:46:01 AM7/9/14
to rs...@googlegroups.com
Duck type means that it will respond to that method, instance of will check the class of the object.

Sent from my phone please excuse my brevity.
--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/CAKxHnE07XU87uRisRMiPn39ms0TLDF8hxT1JTgTE1EK1QFVziQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Arup Rakshit

unread,
Jul 9, 2014, 5:34:43 AM7/9/14
to rs...@googlegroups.com
On Wed, Jul 9, 2014 at 2:15 PM, Sam Phippen <samph...@googlemail.com> wrote:
Duck type means that it will respond to that method, instance of will check the class of the object.

Ah! Got it.

describe '#duck_type' do
  let(:dbl) { double() }
  before { allow(dbl).to receive(:random_method).with(duck_type(:size)) }

  context "when the argument is String" do
    it "should match duck type with one method" do
      dbl.random_method([])
    end
  end

  context "when the argument is Array" do
    it "should match duck type with one method" do
      dbl.random_method("")
    end
  end
end

Result :-

arup$ rspec test_spec.rb 
..

Finished in 0.00094 seconds
2 examples, 0 failures

Good. But what's the use of to check of if any argument to respond to a specific method or not. Is it indirect check to see if the argument object belongs to a specific class or not ? I mean, I want my #foo method always accept arguments as String object only, not any other. Is this the check that duck_type helps us to perform ? Or Am I completely wrong, there is some thing more interesting concept behind it ?


Regards,
A.R




Sam Phippen

unread,
Jul 9, 2014, 5:40:21 AM7/9/14
to rs...@googlegroups.com
Imagine you're building a method which can have several types of object passed in to it. It is logical to assume that you're Going to do roughly the same thing with those objects. As such one checks what methods the thing responds to rather than the type of the thing. 


Sent from my phone please excuse my brevity.
--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages