Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRYing repeated specs in RSpec

Tags:

ruby

rspec

dry

In the test below, the Bar and Baz blocks contain identical specs.

Leaving aside why such repetition was necessary in the first place, I'm wondering how one could dry this up.

I tried turning the blocks into objects and calling them under Bar and Baz, but possibly because I did not get the scopes right, I have not been able to make it work.

describe Foo do
  describe Bar do
    before(:each) do
      prepare
    end

    it "should do something" do
      true
    end

    it "should do something else" do
      true
    end
  end

  describe Baz do
    before(:each) do
      prepare_something_else
    end

    it "should do something" do
      true
    end

    it "should do something else" do
      true
    end
  end
end
like image 222
Hakan Ensari Avatar asked Oct 26 '22 17:10

Hakan Ensari


1 Answers

you might want to create macros. here are some tutorials:

http://www.benmabey.com/2008/06/08/writing-macros-in-rspec/
http://intridea.com/2009/5/15/make-it-so-with-rspec-macros?blog=company
http://railscasts.com/episodes/157-rspec-matchers-macros

like image 163
rubiii Avatar answered Nov 01 '22 19:11

rubiii