Repository navigation
Before block example
Cyril Kato edited this page Nov 1, 2026
·
2 revisions
before runs before each example of the group, after the blocks of the enclosing groups and those written before it in the group, in the example itself: an instance variable set there is seen by the example.
require "r_spec"
RSpec.describe Array do
before do
@elements = []
end
describe "initialized in before" do
it "has 0 elements" do
expect(@elements.count).to be(0)
end
context "when a new element is added" do
before do
@elements << 1
end
it "has 1 element" do
expect(@elements.count).to be(1)
end
end
end
describe "with two blocks in one group" do
before { @elements << :a }
before { @elements << :b }
it "runs them in their order" do
expect(@elements).to eq %i[a b]
end
end
end$ ruby spec/before_spec.rb
spec/before_spec.rb:10: Success: expected 0 to be 0
spec/before_spec.rb:19: Success: expected 1 to be 1
spec/before_spec.rb:29: Success: expected [:a, :b] to eq [:a, :b]