Skip to content

Instantly share code, notes, and snippets.

@cupakromer
Created July 15, 2014 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cupakromer/974c6fb9d0d6de3c2a6e to your computer and use it in GitHub Desktop.
Save cupakromer/974c6fb9d0d6de3c2a6e to your computer and use it in GitHub Desktop.
Various way to test for monkey patching with RSpec 3's `instance_double`
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
@neohunter
Copy link

if this is a file in initializer, where should go the spec file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment