Skip to content

Instantly share code, notes, and snippets.

@nistude
Created November 27, 2011 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nistude/1397967 to your computer and use it in GitHub Desktop.
Save nistude/1397967 to your computer and use it in GitHub Desktop.
double('Foo') vs. Demeter's Law
# in Rails
class BarCollection
def initialize
@bars = [Bar.new, Bar.new]
end
def get_bars
@bars
end
end
class Foo
def do_something
bars = BarCollection.new.get_bars
bars.each do |bar|
bar.something
end
end
end
-----
require 'foo'
require 'bar_collection'
describe Foo do
it 'does something' do
bars = doube(BarCollection)
bars.should_receive(:get_bars).and_return([double('Bar').as_null_object])
foo = Foo.new
foo.do_something
end
end
@dchelimsky
Copy link

The demeter violation is in Foo#do_something. That would be there whether the spec had a double in it or not.

@nistude
Copy link
Author

nistude commented Nov 27, 2011

That's exactly what I meant. Using double('Bar') in my spec corelates with the demeter violation (and tell don't ask). So I rewrote Foo#do_something to call a new method BarCollection#do_something_on_all_bars. With this, I no longer need double('Bar') in the Foo spec.
double('Bar') is no way a problem, it just hints me at a problem in my code after I was happy to find a use case for it (instead of using doube(Bar)).

@dchelimsky
Copy link

I see what you're saying, but you'd see the LoD violation if the spec said bars.should_receive(:get_bars).and_return([Bar.new]) as well. It's not using double('Bar') that gets you there - it's setting the return value on should_receive. Make sense?

@nistude
Copy link
Author

nistude commented Nov 27, 2011

Excellent point, hadn't thought that far. Thanks! :)

@dchelimsky
Copy link

That's actually a very interesting point, however. I think a blog post is in order!

@nistude
Copy link
Author

nistude commented Dec 2, 2011

just wrote up my learnings of the last couple of days: http://blog.nistu.de/2011/12/02/an-epiphany-in-test-driven-development/

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