【问题标题】:FakeFS and Rspec incosistency with Rspec and real filesystemFakeFS 和 Rspec 与 Rspec 和真实文件系统不一致
【发布时间】: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


    【解决方案1】:

    我在创建该问题后找到了答案,duh ;) 我查看了该库的来源并找到了suspicious line

    而不是FakeFS::SpecHelpers,我包含FakeFS::SpecHelpers::All,这是相同的代码,除了FakeFS::FileSystem 在每次调用后不会被清除,现在它的行为正确。

    【讨论】:

    • 包含 FakeFS::SpecHelpers::All 是什么意思?您是否将其包含在使用 fakefs 的每个文件中?还是在 spec_helper.rb 中?
    • 我的意思是spec_helper.rb
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多