[rspec-users] Specifying mixins

Tom Stuart tom at experthuman.com
Tue Nov 6 09:11:00 EST 2007


On 6 Nov 2007, at 02:00, Jim Lindley wrote:
> Add an additional describe block for the class that you're including
> the module into, and then setup a genericly named object in the before
> block
[...]
>
> # page_spec.rb
> describe Page, "should include publishing features" do
>  include PublishableSpec
>
>  before(:each) do
>    @model = Page.new(:title => "title", :content => "content",
> :published => false)
>  end

Yeah, this is fine for a simple mixin with only one shared behaviour,  
but the problem is that a real chunk of mixed-in functionality will  
probably need many behaviours that correspond to different initial  
states (provided you're behaving yourself and not doing too much state  
setup within the individual examples).

So, firstly, perhaps I'll have ten shared behaviours to specify my  
mixin -- do I have ten calls to it_should_behave_like in the spec for  
each target class?

And secondly, perhaps each of those shared behaviours is talking about  
an object with different initial state, e.g. constructed with  
different arguments (a published thing, an unpublished thing, a  
published but deleted thing) -- how do I arrange for that to happen?  
Ten corresponding behaviours each containing the appropriate  
before(:each) and a call to it_should_behave_like? Or arrange for the  
shared behaviours to somehow do the initialisation themselves, e.g. by  
doing some kind of parameterized helper gymnastics where you pass in  
the child class object and the shared behaviour calls #new on it?

None of this is impossible to do, it's just that it all feels very  
repetitious and difficult in contrast to the elegant solutions that  
people often post here. I'm hoping that this sort of "okay, you  
understand the basics, but NOW what?" issue is the kind of thing that  
the hotly-anticipated RSpec book will address, because any information  
about best practice in this area is really lacking, but I fear it  
might not be that kind of book!

Cheers,
-Tom


More information about the rspec-users mailing list