Instructions
Create a function with_counter that:
1. Takes a counter array (to track calls) and a block
2. Adds :started to counter
3. Yields to the block
4. Adds :finished to counter (ALWAYS, even if error)
Use ensure for code that must run:
ruby
begin
yield
ensure
# always runs
end
Hints:
- Add :started before yield
- Add :finished in ensure block
- ensure runs even if error occurs
Your Code
def with_counter(counter) counter << :started yield ensure counter << :finished end
RSpec.describe "with_counter" do
it "tracks start and finish" do
counter = []
with_counter(counter) { "work" }
expect(counter).to eq([:started, :finished])
end
it "finishes even with error" do
counter = []
begin
with_counter(counter) { raise "oops" }
rescue
end
expect(counter).to eq([:started, :finished])
end
end
Results
Click "Run Tests" to see results