如何在RSpec中验证目录不存在时返回预期结果false?
解决RSpec中“期望路径不是目录”的断言问题
这个问题在RSpec里很常见——直接用!be_directory会报错,是因为Ruby会先对be_directory匹配器对象取反,得到布尔值,而expect(...).to需要接收的是匹配器对象,不是布尔值,所以语法不成立。
正确的做法是用RSpec专门提供的否定断言语法:not_to(或者等价的to_not),替换掉原来的to,就能表达“期望不满足某个匹配器”的逻辑了。
修改你的测试代码如下:
context 'when a logfile is given' do it 'does not contain a folder first' do logfile = '/tmp/qwertyasd/random/path/rspec.log' # 用 not_to 实现“不是目录”的断言 expect(Pathname(File.dirname(logfile))).not_to be_directory end it 'create a folder for it' do logfile = '/tmp/qwertyasd/random/path/rspec.log' Pathname.new(logfile).parent.descend { |path| FileUtils.mkdir path if path.parent.writable? && !path.exist? } expect(Pathname(File.dirname(logfile))).to be_directory `rm -rf /tmp/qwertyasd` end end
补充说明:
not_to和to_not是完全等价的,选哪个取决于个人习惯,前者在RSpec社区更常用;- 这个逻辑适用于所有RSpec匹配器,比如要断言数组不为空,可以写
expect(array).not_to be_empty,断言两个值不等可以写expect(a).not_to eq(b)。
内容的提问来源于stack exchange,提问作者Mirwais
相关产品推荐
相关产品推荐

