[rspec-users] Formatting shared example descriptions with test data

Wincent Colaiuta
Mon, 26 Jul 2010 07:55:55 -0000

El 26/07/2010, a las 09:31, Ashley Moran escribi?:

> I''m back again, and still on a quest to tame shared example to do
my bidding.  This time what I''m wondering is... is there any way to
format shared example specdoc description output with data passed in with #let,
or otherwise?  eg: How do I get "1" and "2" into either of
the placeholders here?
>
>  shared_examples_for "Comparable" do
> describe "comparing " do
> it "defines equality for " do
>        object.should eq object
>      end
>    end
>  end
>
>  describe Integer do
>    it_should_behave_like "Comparable" do
>      let(:object) { 1 }
>    end
>    it_should_behave_like "Comparable" do
>      let(:object) { 2 }
>    end
>  end
>
> (If I had to duplicate the 1 and 2 that wouldn''t be the end of the
world, as long as the syntax for including the shared examples was simple
enough.)

Seems to me that including the same shared example group twice in the same
"describe" block is a bit of an abuse, to be honest. I don''t
think it was ever really intended to be used in that way.

Your shared_examples_for should be written in such a way that they
don''t need to reference ""; ie:

  shared_examples_for "Comparable" do
    it ''defines equality'' do
      subject.should eq(subject)
    end
  end

And then you use it like this:

  describe Integer do
    [1, 2].each do |i|
      describe i do
        it_should_behave_like ''Comparable''
      end
    end
  end

Obviously this is a toy example that you''ve given us, and I
don''t see why you''d want to test 1 and 2 like that, but for
the purposes of illustration... The specdoc output for that would look like:

  Integer
    1
      it should behave like Comparable
        defines equality
    2
      it should behave like Comparable
        defines equality

I know you probably have some real example in mind hiding behind that toy
example, but I believe anything you want to test can be written in the same way
(ie. without needing to inject the "" into your shared
examples).

Cheers,
Wincent