Skip to content

Instantly share code, notes, and snippets.

@bravoecho
Created May 17, 2012 17:13
Show Gist options
  • Save bravoecho/2720272 to your computer and use it in GitHub Desktop.
Save bravoecho/2720272 to your computer and use it in GitHub Desktop.
Global hard-coded dependencies are bad not only for design-related matters.
class MyEvilDependency
def self.do_good
"ok"
end
def self.save_the_world
puts "I could destroy the world if I wanted"
end
end
class InjectedDependency
def do_good
"ok"
end
def save_the_world
puts "I would destroy the world but I can't"
end
end
class NaiveClass
def do_something
MyEvilDependency.do_good
MyEvilDependency.save_the_world
end
end
class AnotherClass
def initialize(other_obj)
@other_obj = other_obj
end
def do_something
@other_obj.do_good
@other_obj.save_the_world
end
end
describe NaiveClass do
describe "#my_other_method" do
it "trusts MyEvilDependency" do
MyEvilDependency.should_receive(:do_good)
NaiveClass.new.do_something
end
end
end
describe AnotherClass do
describe "#do_something" do
let(:obj) { double }
it "does what I want" do
obj.should_receive(:do_good)
AnotherClass.new(obj).do_something
end
end
end
# $ rspec global_dependency.rb
# I could destroy the world if I wanted
# .F
#
# Failures:
#
# 1) AnotherClass#do_something does what I want
# Failure/Error: @other_obj.save_the_world
# Double received unexpected message :save_the_world with (no args)
# # ./global_dependency.rb:35:in `do_something'
# # ./global_dependency.rb:56:in `block (3 levels) in <top (required)>'
#
# Finished in 0.00103 seconds
# 2 examples, 1 failure
#
# Failed examples:
#
# rspec ./global_dependency.rb:53 # AnotherClass#do_something does what I want
@bravoecho
Copy link
Author

Basically, you have no control over the side effects of a global dependency.

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