Forked from cupakromer/gist:974c6fb9d0d6de3c2a6e
Last active
August 29, 2015 14:04
-
-
Save Integralist/2766987ada9ac13aa9b0 to your computer and use it in GitHub Desktop.
Test "Duck Typing" using RSpec 3's `instance_double`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Calculator | |
def reduce(operator) | |
fail "You shouldn't be calling this directly!" | |
end | |
end | |
def uses_a_duck_type(calculation) | |
calculation.reduce(:+) | |
end | |
RSpec.describe "various ways to use instance_double with duck typing" do | |
context "defining a local module to document the duck type" do | |
duck_type = Module.new do | |
def reduce(operator) | |
fail "You shouldn't be calling this directly!" | |
end | |
end | |
it "works as expected with duck types" do | |
stubbed_calculator = instance_double(duck_type, reduce: 2) | |
expect(uses_a_duck_type(stubbed_calculator)).to eq 2 | |
end | |
end | |
context "using the assumed Calculator class" do | |
it "works with we intended" do | |
stubbed_calculator = instance_double("Calculator", reduce: 5) | |
expect(uses_a_duck_type(stubbed_calculator)).to eq 5 | |
end | |
end | |
context "using a common object which quacks properly" do | |
it "works with an Array as well" do | |
stubbed_calculator = instance_double("Array", reduce: :ohmy) | |
expect(uses_a_duck_type(stubbed_calculator)).to eq :ohmy | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment