块范围之前的Rspec不一致

时间:2013-07-05 12:38:37

标签: ruby-on-rails ruby testing rspec

使用RSpec的`before(:all)'块时,我遇到了范围问题。

以前我使用的是before(:each),效果很好:

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

但是在(:all)之前切换嵌套的before(:each) block to意味着加载器是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

那么为什么@loader nil在before(:all)块中,而不是在before(:each)块中?

2 个答案:

答案 0 :(得分:5)

所有:all块都发生在任何:each块之前:

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

输出:

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

答案 1 :(得分:3)

根据Rspec documentation on hooksbefore :all挂钩在before :each之前运行。