使用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)块中?
答案 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 hooks,before :all
挂钩在before :each
之前运行。