ruby 和 rspec 的新手 我正在尝试测试一个打开并写入文件的类。
类名是SimpleLogger
这是生成错误的规范:
describe SimpleLogger do
...
context 'when using a file' do
require 'fakefs/spec_helpers'
before(:all) do
@path = 'my_file'
logger = SimpleLogger.new @path
logger.write "Hello, world!"
logger.close
end
...
it 'we expect the file to have a valid content' do
expect(File.read(@path)).to eq "Hello, world!\n"
end
end
end
产生的错误是:
Failure/Error: expect(File.read(@path)).to eq "Hello, world!\n"
expected: "Hello, world!\n"
got: ""
(compared using ==)
Diff:
@@ -1,2 +1 @@
-Hello, world!
该文件存在于我的文件系统中,当我在一个独立的 ruby 文件上测试一个简单的 puts Find.read("my_file")
时,我得到了预期的结果。
我在没有 fakefs gem
为什么在规范中运行时它不起作用? 除此之外,我无法理解 fakefs 的优势,因为它创建的文件完全相同。那么为什么要使用fakefs呢? 当它创建文件时,我应该在规范内删除它吗?
提前致谢;)
最佳答案
来自documentation - 似乎您需要包含帮助程序来激活 FakeFS
:
FakeFS::SpecHelpers
provides a simple macro for RSpec example groups to turn FakeFS on and off. To use it simply require 'fakefs/spec_helpers', then include FakeFS::SpecHelpers into any example groups that you wish to use FakeFS in. For example:require 'fakefs/spec_helpers' describe "Some specs that deal with files" do include FakeFS::SpecHelpers ... end
By default, including FakeFS::SpecHelpers will run for each example inside a describe block. If you want to turn on FakeFS one time only for all your examples, you will need to include FakeFS::SpecHelpers::All.
Alternatively, you can include FakeFS::SpecHelpers in all your example groups using RSpec's configuration block in your spec helper:
require 'fakefs/spec_helpers' Spec::Runner.configure do |config| config.include FakeFS::SpecHelpers end
If you do the above then use_fakefs will be available in all of your example groups.
您还需要使用 before(:each)
而不是 before(:all)
- 就像许多单元测试助手一样,FakeFS
坚持单元测试隔离原则,其中一个测试的副作用不应影响另一个测试。这就是为什么在每次测试后,gem 都会“重置”其容器的状态,并清除其中的所有文件。
关于ruby - 使用 rspec 进行测试时,对于非空文件,File.read 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078818/