RSpec测试遇sleep时其他Context内容提前输出?原因问询
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.
Loading Phase: When RSpec first reads your test file, it executes all code directly inside
context/describeblocks (but not code wrapped init/specifytest cases). Yourputs "hello"andputs "thanks"are both sitting straight incontextblocks, not tied to any test-specific logic. So RSpec runs theseputsstatements immediately as it parses the file—way before it starts executing the actual test code in youritblocks.Running Phase: Only code inside
itblocks (and RSpec hooks likebefore,after, etc.) gets executed during the actual test run. That means thesleep(50)in your firstitblock doesn't start until after RSpec has finished loading all your test code—including running bothputsstatements.
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:
- The first
itblock runs, prints "hello", then sleeps for 50 seconds - Next, the second context's
before(:example)runs and prints "thanks" - Finally, the second
itblock executes
This matches the flow you originally expected!
内容的提问来源于stack exchange,提问作者AutomateFr33k

