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

Wincent Colaiuta win at wincent.com
Mon Jul 26 03:55:55 EDT 2010


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 <i> here?
> 
>  shared_examples_for "Comparable" do
>    describe "comparing <i>" do
>      it "defines equality for <i>" 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 "<i>"; 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 "<i>" into your shared examples).

Cheers,
Wincent



More information about the rspec-users mailing list