问题
So here's my problem:
I am writing unit tests for my Rails models and I have a whole set of examples that each require the same setup in order to run. If I'm not mistaken, the usual way to set things up the same way for multiple RSpec tests is to use a before(:each) block, like this:
describe Model do
before(:each) do
# Complex setup
end
# Examples
end
Unfortunately the set of examples which needs this setup is starting to get rather large, and completing this complex setup proceedure for each and every test takes a long time. I tried doing this:
describe Model do
before(:all) do
# Complex setup
end
# Examples
end
But this method doesn't roll back my setup though after I'm done with it, which causes problems in later tests. What I really want is to do something like this:
describe Model do
around(:all) do |examples|
transaction do
# Complex setup
examples.run
raise ActiveRecord::Rollback
end
end
# Examples
end
RSpec doesn't currently support an around(:all) hook however. Any ideas?
回答1:
The easiest way to do this would just be to use an after(:all)
block to clean up after your tests.
来源:https://stackoverflow.com/questions/12646871/optimising-rspec-tests-to-avoid-repeating-complex-setup-proceedures