I have some expensive test setup that is only necessary for a handful of examples in my spec, and, if necessary, it only needs to run once. Because it is slow, I am trying to avoid putting it in a before(:each) block, but before(:all) doesn’t seem to suit my needs. I think a complicating factor is that the expensive part must run AFTER some other common setup. (This is a capybara test for an app with a search engine. After creating some records, I need to index the test database in order to get search results.) My setup is like this:
feature 'some particular feature' do
before(:each) do
# a bunch of common test setup (creating records that this test will use)
end
describe 'simple example #1' do
# a simple example that doesn't need the expensive setup
end
.
.
.
describe 'simple example #N' do
# a simple example that doesn't need the expensive setup
end
describe 'a more complicated example' do
before(:all) do
# expensive_setup that depends on the records created above
end
it 'does something' do ... end
it 'does something else' do ... end
.
.
.
it 'even does this' do ... end
end
end
The problem is that when rspec is running the examples in the context with the more complicated example, the before(:all) block runs before the before(:each) block that it depends on. So far I have had to put the expensive setup in a before(:each) block instead of a before(:all) block. This means that the expensive setup has to run for each it block inside that example. Is there a better way to do this?
Update:
I failed to mention that the result of the expensive operation depends only on the database. Therefore, since each example uses the same database setup, it would be safe to re-use the result of the expensive operation for each example. Also, the result lives in the filesystem, so it won’t be cleared between examples.
I’m thinking the way to go is to put some sort of marker in the filesystem indicating that the result is good and doesn’t need to be re-calculated.
I wound up working around the problem by calculating a digest of the common setup and saving that along with the results of expensive operation. Before doing the expensive operation, check if the current digest matches the one on disk. If so, there is no need to do it. Since all the examples share the common setup, the expensive operation only runs at most once.