【问题标题】:Seeing if a file exists with Rspec使用 Rspec 查看文件是否存在
【发布时间】:2014-03-05 18:31:19
【问题描述】:

我有一个文件,我需要在运行存根时查看它是否存在,但在测试时该文件的位置是不确定的。我有一些关于我认为它可能如何工作的pseducode,但我认为有些东西仍然不正确。基本上,实际代码运行 Dir.glob("/opt/test-*/bin/progname").exists?看看那里有没有文件。我需要把它分成多于 1 行吗?

Dir.stubs(:glob).with("/opt/test-*/bin/progname").exists?returns(true)

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    如果您将Dir.glob 存根,那么您将不会测试您是否正确调用它。相反,您实际上可以在示例设置中将文件写入测试位置:

    before(:each) do 
      FileUtils.cp source, destination
    end
    

    然后清理它:

    after(:each) do
      FileUtils.rm destination
    end
    

    【讨论】:

      【解决方案2】:

      您尝试的正确变化是: Dir.stubs(:glob).with("/opt/test-*/bin/progname").and_return(double("glob", :'exists?' => true)

      您可以改用FakeFS gem 来模拟文件系统:

      FakeFS.activate!
      
      File.open('/opt/test-this/bin/progname', 'w') { |f| f.write('something') }
      

      【讨论】:

        猜你喜欢
        • 2020-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        • 2013-11-10
        • 1970-01-01
        • 2015-05-18
        • 2016-08-25
        相关资源
        最近更新 更多