describe 'Feature' do
before do
setup
end
describe 'Success' do
before do
setup_for_success
end
specify 'It works' do
...
end
end
end
RSpec将始终在setup
之前运行setup_for_success
。有没有办法先运行setup_for_success
?
答案 0 :(得分:3)
您可以通过确定before(:all)
在before(:each)
尝试此操作之前运行来实现此目的:
describe 'Feature' do
before(:each) do
puts "second"
end
describe 'Success' do
before(:all) do
puts "first"
end
specify 'It works' do
...
end
end
end
# =>
10:29:54 - INFO - Running: spec
Run options: include {:focus=>true}
first
second
.
Finished in 0.25793 seconds (files took 2.52 seconds to load)
1 example, 0 failures
编辑:
在Rspec 2中,操作按此顺序运行:
before suite
before all
before each
after each
after all
after suite
以下是显示调用方法顺序的文档的链接:https://www.relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks#before/after-blocks-are-run-in-order
显然在Rspec 3.5中,前块调用具有不同的命名也可以。它们按此顺序运行:
before :suite
before :context
before :example
after :example
after :context
after :suite
describe 'Feature' do
before(:example) do
puts "second"
end
describe 'Success' do
before(:context) do
puts "first"
end
specify 'It works' do
...
end
end
end
10:59:45 - INFO - Running: spec
Run options: include {:focus=>true}
first
second
.
Finished in 0.06367 seconds (files took 2.57 seconds to load)
1 example, 0 failures
以下是较新的文档: http://www.relishapp.com/rspec/rspec-core/v/3-5/docs/hooks/before-and-after-hooks
答案 1 :(得分:2)
before
过滤器按照指定的顺序附加。从RSpec 2.10.0开始,您可以通过使它们成为prepend_before
过滤器来添加它们。
同样,after
过滤器默认为预先添加,但您可以append_after
代替它们。
您的代码最终会如下所示(为简洁起见):
describe 'Feature' do
before { setup }
describe 'Success' do
prepend_before { setup_for_success }
it 'works' { ... }
end
end
答案 2 :(得分:0)
您似乎在嵌套上下文中添加了外部所需的内容,这有点奇怪。我怀疑您在所有嵌套上下文中都不需要该设置。如果是这种情况,则需要过滤钩子。
RSpec.describe 'Feature' do
before :each, success: true do
setup_for_success
end
before :each do
setup
end
describe 'Success', success: true do
specify 'It works' do
...
end
end
describe 'Fail' do
specify 'Won´t work' do
...
end
end
end
您可以不进行嵌套:
RSpec.describe 'Feature' do
before :each, success: true do
setup_for_success
end
before :each do
setup
end
specify 'It works', success: true do
...
end
specify 'Won´t work' do
...
end
end
这是文档的链接: