Skip to content

Commit

Permalink
+ tempdir_for
Browse files Browse the repository at this point in the history
  • Loading branch information
kschiess committed Oct 25, 2010
1 parent 486fc0e commit 785bfcf
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 20 deletions.
45 changes: 25 additions & 20 deletions lib/toolshack.rb
Expand Up @@ -5,6 +5,10 @@
# place and that I just don't want to write again.
#
module Toolshack
def self.included(by)
by.extend(ClassMethods)
end

# Creates a temporary directory and returns its path to the caller. Note
# that this can also be used in block style:
#
Expand Down Expand Up @@ -37,26 +41,27 @@ def temporary_directory(base)
end
module_function :temporary_directory

# Use this in rspec to create and manage a tempdir at the same time. Roughly
# aequivalent to this:
#
# attr_reader :tempdir
# around(scope) { |example|
# temporary_directory do |path|
# @tempdir = path
# example.run
# end
# end
#
def tempdir_for(scope, name=:tempdir)
attr_reader name
module ClassMethods
# Use this in rspec to create and manage a tempdir at the same time. Roughly
# aequivalent to this:
#
# attr_reader :tempdir
# around(scope) { |example|
# temporary_directory do |path|
# @tempdir = path
# example.run
# end
# end
#
def tempdir_for(scope, base, name=:tempdir)
attr_reader name

around(scope) { |example|
temporary_directory do |path|
instance_variable_set("@#{name}", path)
example.run
end
}
around(scope) { |example|
temporary_directory(base) do |path|
instance_variable_set("@#{name}", path)
example.run
end
}
end
end
module_function :tempdir_for
end
28 changes: 28 additions & 0 deletions spec/unit/toolshack_spec.rb
Expand Up @@ -28,4 +28,32 @@ def call
call.should_not == call
end
end
describe "<- .tempdir_for" do
tempdir_for(:each, 'tempdir_for')
subject { tempdir }

it { should_not be_nil }
it "should be a directory" do
File.directory?(tempdir).should == true
end

2.times do |i|
# Create and clean a tempdir twice. There should be no junk left lying
# around.
let(:tempdirs) { [] }

context "when creating more than one temporary directory (#{i+1})" do
tempdir_for(:each, 'tempdir_for')

before(:each) { tempdirs << tempdir }

it "should have at most one directory alive" do
(tempdirs - Array(tempdir)).each do |path|
File.exist?(path).should == false
end
end
end
end

end
end

0 comments on commit 785bfcf

Please sign in to comment.