[rspec-users] reusable specs - almost there

David Chelimsky
Sun, 05 Aug 2007 15:57:38 -0000

On 8/4/07, David Green <justnothing at tiscali.co.uk>
wrote:
>
> I have a lot of controllers with virtually identical functionality for most
> actions. I''ve been using shared behaviours to DRY things up a bit,
but I
> still have to create separate behaviours for each context before I can use
> the shared behaviours
>
> what I have now is a generic file which contains all the behaviours and
> examples common to all the controllers, and that file gets loaded from an
> actual controller spec. The generic file knows which controller to test by
> calling kontroller(), which is defined in the controller spec.
>
> here''s a very simplified example:
> http://pastebin.com/m6b47bae9
>
> It works great when I run the specs individually, but when I use rake,
specs
> begin to fail and i think it''s because the value of kontroller()
is set to
> whatever it returns the first time it gets called. Here''s the rake
output
> from running the specs shown above:
>
>
> FooController
> .FooController
> .
>
> Finished in 0.041793 seconds
> 2 examples, 0 failures
>
> I would expect it to print FooController and then BarController ...
> interestingly, if I insert ''puts kontroller.to_s''
*outside* of the describe
> block, then it does output the names of both controllers as expected.
>
> does anyone know of a solution?
> thanks
>
> dave

I''m all for keeping things DRY, but NEVER at the risk of clarity.
You''ve got to balance DRY and readability/clarity. Anybody familiar
with rspec can look at this:

========================describe FooController do
  it_should_behave_like "All Controllers"
end
========================
and understand what that means: A FooController should behave like All
Controllers. Perhaps there is a split second of mental mapping: "Oh,
there must be some behaviour described for all controllers that the
FooController should adopt."

Compare that to your example:

========================def kontroller
  FooController
end

load File.dirname(__FILE__) + ''/all_controllers.rb''
========================
First of all - how is that any more DRY than the example above?
Perhaps you save a few keystrokes, but if you think that makes it more
DRY then you don''t really understand what DRY is all about.

Second of all, what does it actually mean? Where''s the story? How is a
non-developer going to look at that and have any context for what that
means? I''m a developer and I don''t know what it means. Sure I
can
figure it out, but, in my opinion, it''s just nowhere near as clear as
the example above.

FWIW,
David