Reputation: 6483
I have a context
block in rspec with multiple it
blocks inside it. I want to run a before block to set up data for the it
blocks but this data takes a long time to set up and is being used to read only. rspec before(:each)
creates and deletes this data after every it block which takes a long time. before(:all)
creates the data at the start of all the tests and doesn't delete it.
Is there any way I can have this data created just within the context
block and deleted after?
Upvotes: 1
Views: 1156
Reputation: 10056
Since RSpec 3 these are officially named before/after(:{example,context})
(see docs).
What you want to accomplish can be done with a before(:context)
where you set up the data and an after(:context)
where you clean it up.
RSpec.describe Thing do
before(:context) do
@thing = Thing.new
end
after(:context) do
@thing.delete
end
it "has 0 widgets" do
expect(@thing.widgets.count).to eq(0)
end
it "can accept new widgets" do
@thing.widgets << Object.new
end
it "shares state across examples" do
expect(@thing.widgets.count).to eq(1)
end
end
Upvotes: 3