Undistraction
Undistraction

Reputation: 43589

Rspec before block scope inconsistant

I'm having scope issues when using RSpec's `before(:all)' block.

Previously I was using before(:each), which worked fine:

module ExampleModule

    describe ExampleClass

        before(:each) do

            @loader = Loader.new

        end

        ...


       context 'When something' do


            before(:each) do
                puts @loader.inspect # Loader exists
                # Do something using @loader
            end

            ...

        end

    end

end

But switching the nested before(:each) block tobefore(:all) means loader is nil:

module ExampleModule

    describe ExampleClass

        before(:each) do

            @loader = Loader.new

        end

        ...


        context 'When something' do


            before(:all) do
                puts @loader.inspect # Loader is nil
                # Do something using @loader
            end

            ...

         end

    end

end

So why is @loader nil in the before(:all) block, but not in the before(:each) block?

Upvotes: 1

Views: 947

Answers (2)

Neil Slater
Neil Slater

Reputation: 27207

All the :all blocks happen before any of the :each blocks:

describe "Foo" do
  before :all do
    puts "global before :all"
  end

  before :each do
    puts "global before :each"
  end

  context "with Bar" do
    before :all do
      puts "context before :all"
    end

    before :each do
      puts "context before :each"
    end

    it "happens" do
      1.should be_true
    end

    it "or not" do
      1.should_not be_false
    end
  end
end

Output:

rspec -f d -c before.rb

Foo
global before :all
  with Bar
context before :all
global before :each
context before :each
    happens
global before :each
context before :each
    or not

Upvotes: 5

BaronVonBraun
BaronVonBraun

Reputation: 4293

As per the Rspec documentation on hooks, before :all hooks are run prior to before :each.

Upvotes: 3

Related Questions