[rspec-users] Difference between :each and :all

John Feminella johnf at distb.net
Thu Jan 27 18:13:00 EST 2011

Here's an illustrative example that should clear things up:

require 'spec_helper'

describe "behavior of before-each and before-all" do
  before(:all) { puts "-- running :all" }
  before(:each) { puts "-- running :each" }

  describe "addition" do
    it "should add two and two" do
      (2 + 2).should == 4

    it "should add three and three" do
      (3 + 3).should == 6

    it "should add four and four" do
      (4 + 4).should == 8

  describe "multiplication" do
    it "should raise two to two" do
      (2 ** 2).should == 4

    it "should raise three to three" do
      (3 ** 3).should == 27

    it "should raise four to four" do
      (4 ** 4).should == 256

And here's the result:

behavior of before-each and before-all
-- running :all
-- running :each
    should add two and two
-- running :each
    should add three and three
-- running :each
    should add four and four
-- running :each
    should raise two to two
-- running :each
    should raise three to three
-- running :each
    should raise four to four

Finished in 0.0034 seconds
6 examples, 0 failures

Notice how :each runs before _each_ spec, but :all runs once, before _any_spec.
John Feminella
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/fjsquared
SO: http://stackoverflow.com/users/75170/

On Thu, Jan 27, 2011 at 17:56, Brian Warner <lists at ruby-forum.com> wrote:
> I'm having a hard time grasping the difference between :each and :all.
> If I have a bunch of stuff inside a "before :each" block. Everytime I
> try to run an example that block of code will be run before the example.
> Now if I had the same code inside a "before :all" block. Everytime an
> example is run, that block will still be run. Yielding the same results.
> At least in my mind.
> The RSpec book says something like "before :each" defines a state for
> each example. "before :all" defines a state for all the examples. But
> what's the difference?
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

More information about the rspec-users mailing list