1

使用 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

但是切换嵌套的before(:each) block tobefore(:all) 意味着 loader 为零:

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 在 before(:all) 块中是 nil 而不是在 before(:each) 块中呢?

4

2 回答 2

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
于 2013-07-05T12:45:41.817 回答
3

根据关于钩子的 Rspec 文档before :all钩子在before :each.

于 2013-07-05T12:45:40.207 回答