You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:15:59