[rspec-users] advice on a spec'ing best practice

Jeremy Burks jeremy.burks at gmail.com
Wed Feb 7 12:14:20 EST 2007


i am in the process of converting the tests in two projects that i am
working on (one rails, one ruby) to rspec. i felt like i was doing ok
applying BDD and using rspec properly until i read a comment in
another topic on the list from David (subject  "long jumping out of
code in specs"). In there it was said:

---
Testing privates is a no-no, but testing that a public method on the
same class gets called is almost as dirty for the same reasons. It's
less likely to be a problem than private methods
because it's more stable (public methods are inherently more stable
than privates), but it still feels like a design smell - especially if
you have to intercept calls to that method (partial mocks), as you are
doing.
---

Hopefully i didn't take that out of context.

This statement got me thinking about how i am witting my sepcs because
i have been intercepting calls to methods on the class that is being
spec'd. I do it mostly to isolate the code being tested as much as
possible.

I am hoping to get some advice on how to spec this method.

class Foo
  def each_project
    projects.each do|project|
       yield(project, project.name)
    end
  end
end

projects is an attribute of class Foo. Normally i would mock the
projects attribute to return an array of mocks. That would allow me to
verify the yield is working as it should. Based on David's comment
that seems to be a smell.

Is that correct?

The alternative i see is to use dependency injection and pass the list
of projects in the initialize method of class Foo. Or maybe inject the
class responsible for initializing the projects.

class Foo
  def initialize(projects)
    @projects = projects
  end
end

Thoughts?


More information about the rspec-users mailing list