[rspec-users] Specifying mixins

Jim Lindley jimlindley at gmail.com
Mon Nov 5 21:00:51 EST 2007


> > just a short advice:
> >
> > describe MyModule do
> >   it "should do something" do
> >     # The module is automatically mixed into your spec
> >   end
> > end
> >
> > Aslak
>
> I suppose it really depends on how static/dynamic the module is.

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 and then include the shared behaviours from the module's spec
module. Like this:

# 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

  it_should_behave_like "Publishable"  # include the shared tests
end

# post_spec.rb
describe Post, "should include publishing features" do
  include PublishableSpec

  before(:each) do
    @model = Post.new(:title => "title", :content => "content",
:published => false)
  end

  it_should_behave_like "Publishable"  # include the shared spec
end

# publishable_spec.rb
module PublishableSpec

  describe "Publishable", :shared => true do
    it "should have a published marker" do
     @model.save!
     @model.should_not be_published
    end

    it "should be publishable" do
     @model.save.publish!
     @model.should be_published
    end

  end
end

I can post more if that's unclear (showing the actual AR classes and
mixin), but it seems to work well and eliminates duplication.  I hope
the formatting on this comes through...

Jim Lindley
http://jimlindley.com


More information about the rspec-users mailing list