我在使用 RSpec 的“before(:all)” block 时遇到范围问题。
之前我使用的是 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 切换为
before(:all) 意味着 loader 为 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) block 中,而不是在 before(:each) block 中?
最佳答案
所有 :all
block 都发生在任何 :each
block 之前:
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
关于ruby-on-rails - block 范围不一致之前的 Rspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17489117/