2

If I have a class like this

class Foo < File
  # fun stuff
end

and I wanted to test that it is indeed inherits from File, I could write

describe Foo
  let(:a_file) { Foo.open('blah.txt') }

  it "is a File" do
    expect(a_file).to be_a File
  end
end

My question is, will the let() take care of closing the file after the example is run? Or do I need to explicitly close the file somewhere.

Or would something like this be better,

it "is a File" do
  Foo.open('blah.txt') do |f|
    expect(f).to be_a File
  end
end

forgetting about the let() entirely?

I looked at using let and closing files for reference, but I'm still unsure.

Community
  • 1
  • 1
Sandy
  • 799
  • 8
  • 12

1 Answers1

3

If you're going to use a_file in just one test, then your second example is good.

it "is a File" do
  Foo.open('blah.txt') do |f|
    expect(f).to be_a File
  end
end

If you'll use a_file multiple times, you could do this:

before do 
 @file = Foo.open('blah.txt')
end

after do
  @file.close
end

it "is a File" do
  expect(@file).to be_a File
end

...
dax
  • 10,779
  • 8
  • 51
  • 86
  • The before and after is a good idea. If you didn't need the file for all your specs, would let work in that case? – Sandy Jan 08 '15 at 16:30
  • if you don't need it for all your tests, just use a block as in your example – dax Jan 08 '15 at 19:53