当我面对
some issue时,我决定在执行钩子之前和之后检查什么顺序.这就是我做的:
require "spec_helper" describe "The order:" do before(:all) { puts "before_all" } after(:all) { puts "after_all" } before(:each) { puts "before_each" } after(:each) { puts "after_each" } describe "DESC A" do before { puts "A_before" } it "A_it_1" do expect(1).to eq(1) end it "A_it_2" do expect(1).to eq(1) end end describe "DESC B" do before { puts "B_before" } it "B_it_1" do expect(1).to eq(1) end it "B_it_2" do expect(1).to eq(1) end end end
我得到了什么:
The order: before_all DESC A before_each A_before after_each A_it_1 before_each A_before after_each A_it_2 DESC B before_each B_before after_each B_it_1 before_each B_before after_each B_it_2 after_all
这里发生了什么 ??为什么after_each在A_it_1之前运行?
更新:
添加(:每个)更有趣:
around(:each) do |example| puts "around_in" example.run puts "around_out" end
和结果:
The order: before_all DESC A around_in before_each A_before after_each around_out A_it_1 around_in before_each A_before after_each around_out A_it_2 DESC B around_in before_each B_before after_each around_out B_it_1 around_in before_each B_before after_each around_out B_it_2 after_all
解决方法
您的输出和relishapp.com上记录的官方输出是正确的.发生的事情是rspec需要在每个示例之后运行after(:each)es,因为after(:each)中的异常会导致示例失败.在rspec可以在输出中显示示例之前,它需要知道它是绿色还是红色,这意味着需要在示例的描述出现在输出之前运行after(:eaches).
但是,如果在实际示例中放置puts语句,您将看到before(:each)es出现在它之前,然后运行示例代码(包括puts),然后是after(:each)es,只是正如您所期望的那样,最后,示例的描述输出到屏幕.
像你一样,我也很困惑,直到我意识到rspec打印出的示例标签与它实际做的不一致 – 标签只在所有之前(:all)s,之前(:每个)打印出来es,以及(:each)之后运行的例子.
注意:在打印完示例标签之后运行(:all)之后运行,因为它们不会影响测试结果(生成警告,表示在after(:all)挂钩中发生异常,但这不是让测试变红).