Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在使用let-in-ruby-rspec时测试和关闭文件对象_Ruby_Testing_Rspec - Fatal编程技术网

在使用let-in-ruby-rspec时测试和关闭文件对象

在使用let-in-ruby-rspec时测试和关闭文件对象,ruby,testing,rspec,Ruby,Testing,Rspec,如果我有这样的课 class Foo < File # fun stuff end 我的问题是,在运行示例后,let()是否会负责关闭文件?或者我需要在某个地方显式关闭文件 还是像这样更好 it "is a File" do Foo.open('blah.txt') do |f| expect(f).to be_a File end end 完全忘记let()了吗 我查看了和以供参考,但我仍然不确定。如果您打算在一个测试中使用a_文件,那么您的第二个示例很好 it

如果我有这样的课

class Foo < File
  # fun stuff
end
我的问题是,在运行示例后,let()是否会负责关闭文件?或者我需要在某个地方显式关闭文件

还是像这样更好

it "is a File" do
  Foo.open('blah.txt') do |f|
    expect(f).to be_a File
  end
end
完全忘记let()了吗


我查看了和以供参考,但我仍然不确定。

如果您打算在一个测试中使用
a_文件
,那么您的第二个示例很好

it "is a File" do
  Foo.open('blah.txt') do |f|
    expect(f).to be_a File
  end
end
如果要多次使用
a_文件
,可以执行以下操作:

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

...

前后对比是个好主意。如果您的所有规格都不需要该文件,那么让它在这种情况下工作好吗?如果您的所有测试都不需要它,请使用示例中的块
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

...