【发布时间】:2013-12-08 22:50:08
【问题描述】:
我正在尝试编写一些涉及文件操作的测试。我想使用一些假文件系统(例如用于外部服务的 VCR),我找到了fakeFS。不幸的是,要么我不能正确设置它,要么有什么东西坏了(我怀疑,这是一个非常基本的功能),我准备了一个简单的例子来说明我的意思,让代码说话:
真正的FS:
module MyModule
describe Something do
before(:all) do
File.open("#{Rails.root}/foo.txt", 'w+') { |f| f.write 'content'}
end
it 'should exist' do
expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true
end
it 'should still exist' do
expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true
end
end
end
运行,给出:
bash-4.2$ rspec
..
Finished in 0.00161 seconds
2 examples, 0 failures
以这种方式添加fakeFS:
require 'fakefs/spec_helpers'
module MyModule
describe Something do
include FakeFS::SpecHelpers
FakeFS.activate!
FakeFS::FileSystem.clone(Rails.root)
before(:all) do
File.open("#{Rails.root}/foo.txt", 'w+') { |f| f.write 'content'}
end
it 'should exist' do
expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true
end
it 'should still exist' do
expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true
end
end
end
结果:
bash-4.2$ rspec
.F
Failures:
1) MyModule::Something should still exist
Failure/Error: expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true
expected: true value
got: false
# ./spec/models/something_spec.rb:23:in `block (2 levels) in <module:MyModule>'
Finished in 0.00354 seconds
2 examples, 1 failure
所以看起来文件没有通过后续测试持久化。我误解了before(:all) 的工作原理还是我做错了什么?如果是这样,那为什么该代码适用于真实文件?
如果它不是一个错误,只是一个特性,那么是否还有其他与真实文件系统 gem 一致的假文件系统 gem?还是我必须保留真实文件才能进行测试……好吧,测试?
【问题讨论】:
标签: ruby-on-rails rspec filesystems rspec-rails