How to get data from global hook before(:all)?

72 views
Skip to first unread message

mmc2...@gmail.com

unread,
Jan 15, 2015, 3:51:22 AM1/15/15
to rs...@googlegroups.com

Hello,

I'm new in Rspec, so I think this is basic question.
(I'm using Rspec 3)

I have 3 spec files and want to use the same tmpdir in my all examples.
I'd like to call before(:all) only once and use the same dir, so I'd like to have it in global hook before(:all).
I'm thinking like below:

spec_helper.rb
-----------------------------
RSpec.configure do |config|
  config.before(:all) do
    @tmpdir = Dir.mktmpdir
    # a lot of things to do here
  end
  config.after(:all) do
    FileUtils.rm_rf(@tmpdir)
  end
end
-----------------------------

target1_spec.rb, target2_spec.rb, target3_spec.rb
-----------------------------
require 'spec_helper'

describe 'test' do
  # I want to use the temp dir name here
end
-----------------------------

When I googled this, somebody suggested to set global variable or constant value in spec_helper in similar situations.
Is there any other good way to get the temp dir name in the spec files?

Thanks,

Makoto

Myron Marston

unread,
Jan 15, 2015, 3:24:36 PM1/15/15
to rs...@googlegroups.com
First off, `config.before(:all)` will run more than once -- it will run once per top level example group.  It's slightly confusing (as `:all` would make you think it would run once before all specs in the entire suite), but it really just adds a `before(:all)` hook to every top-level example group.  If you want a global hook that runs only once, use `before(:suite)` -- that runs once before any examples run, and then `after(:suite)` runs at the end after all examples are complete.  The confusion about `config.before(:all)` is what caused us to introduce `:context` and `:example` in RSpec 3 as aliases for `:all` and `:each` hooks -- `config.before(:context)` is much clearer.

Anyhow, assigning the created temp directory to a constant or global variable works just fine as a way to make it globally available -- you intend it to be a global value, after all.

HTH,
Myron

mmc2...@gmail.com

unread,
Jan 16, 2015, 5:07:10 AM1/16/15
to rs...@googlegroups.com
Hello,
 
Thank you for your answer.
Now I understand about before(:all) and before(:suite), and I will try global value or const value.
 
Thanks,
Makoto
Reply all
Reply to author
Forward
0 new messages