[rspec-users] Factoring out code that creates specs

Matt Wynne matt at mattwynne.net
Mon Sep 15 13:28:00 EDT 2008

It's all gone a bit meta.

I've started noticing patterns in my specs, where I want more than  
one class to satisfy a specific bunch of behaviours.

I know I can use it_should_behave_like and this works in simple  
cases, but I want to be able to iterate around an array of values and  
generate a my bunch of it "should ..." specs for each item in the array.

I know I can do this by going

describe "the cheese factory"
	[:cheddar, :brie, :lancashire].each do |cheese|
		it "should create a valid piece of #{cheese}" do
			Factory.create(cheese).should be_valid

		it "should create a piece of #{cheese} with valid packaging" do
			... etc

...but what if I want to specify other factories too, all of which  
conform to the it blocks I specified above? (e.g. a ToyFactory that  
creates valid toys with valid packaging). How can I factor that spec  
logic out?

I tried putting the content of the (do |cheese|) block into a method,  
but ruby doesn't seem to be able to see that method when the describe  
block runs... I guess I need to maybe patch it into some RSpec class  
instead? Or put it into a module and include it? Am I going down the  
wrong lines? is there an easier way to achieve this?

Sorry if this is a dumb question, I'm bumping up against the  
limitations of my ruby experience again :)


In case you wondered: The opinions expressed in this email are my own  
and do not necessarily reflect the views of any former, current or  
future employers of mine.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20080915/342c0533/attachment.html>

More information about the rspec-users mailing list