You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RSpec测试遇sleep时其他Context内容提前输出?原因问询

Why does puts "thanks" print before sleep(50) finishes in RSpec?

My Test Code

context "example 1" do 
  puts "hello" 
  it "example 1 it" do 
    sleep(50) 
  end 
end 
context "example 2" do 
  puts "thanks" 
  it "example 2 it" end 
end 

Output When Running with Rake

hello thanks example 1 example 1 it <<waits for 50s >>

My Question

Why does thanks print while sleep(50) is still running? I expected it to only show up after the sleep finishes.


Answer

Great question! This all comes down to how RSpec processes your test code—it has two clear phases: loading and running.

  1. Loading Phase: When RSpec first reads your test file, it executes all code directly inside context/describe blocks (but not code wrapped in it/specify test cases). Your puts "hello" and puts "thanks" are both sitting straight in context blocks, not tied to any test-specific logic. So RSpec runs these puts statements immediately as it parses the file—way before it starts executing the actual test code in your it blocks.

  2. Running Phase: Only code inside it blocks (and RSpec hooks like before, after, etc.) gets executed during the actual test run. That means the sleep(50) in your first it block doesn't start until after RSpec has finished loading all your test code—including running both puts statements.

How to Get the Behavior You Want

If you want thanks to print after the first test's sleep completes, you need to move that puts into a part of RSpec that runs during the test execution phase, not the loading phase. For example, use a before(:example) hook in the second context, which runs right before that context's test cases execute:

context "example 1" do 
  it "example 1 it" do 
    puts "hello"
    sleep(50) 
  end 
end 
context "example 2" do 
  before(:example) do
    puts "thanks"
  end
  it "example 2 it" do
    # Add your test logic here
  end 
end 

Now when you run the tests:

  1. The first it block runs, prints "hello", then sleeps for 50 seconds
  2. Next, the second context's before(:example) runs and prints "thanks"
  3. Finally, the second it block executes

This matches the flow you originally expected!

内容的提问来源于stack exchange,提问作者AutomateFr33k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:46:19