【问题标题】:Testing Directory exist with Rspec测试目录与 Rspec 一起存在
【发布时间】:2012-09-15 07:54:09
【问题描述】:

我正在测试lib/pdf_helper.rb。所以我创建了spec/lib 目录。然后我在spec/lib 目录中创建一个文件pdf_helper_spec.rb。因为我正在测试 pdf 文件夹应该在公共文件夹中,这是我的代码

require 'spec_helper'
require 'pdf_helper'

    describe "Pdfhelpers" do
        it "Should be in public folder" do
        file = File.new ("#{Rails.root}/public/pdf")
        if File.exist?(file) == 'true'
            puts "Success"
        else
            puts"failed"
        end


    end
  end

我说的对吗?我是 RSpec 的新手。

【问题讨论】:

标签: ruby-on-rails ruby testing rspec


【解决方案1】:
expect(File).not_to exist("#{Rails.root}/public/pdf")

适用于文件和文件夹。

【讨论】:

    【解决方案2】:

    对于这类事情,路径名也被证明是相当可读的。

    require 'pathname'
    
    # ...
    
    expect(Pathname.new('file.txt')).to exist
    expect(Pathname.new('file.txt')).to be_file
    expect(Pathname.new('dir')).to be_directory
    

    【讨论】:

      【解决方案3】:

      如果你想知道一个文件是否是一个目录,那么你可以使用File.directory?函数。

      【讨论】:

        【解决方案4】:

        我自己研究这个,这是我发现的:

        File.directory?("#{Rails.root}/public/pdf").should be true
        

        【讨论】:

        • 用不朽的 Big Lebowski 的话来说,“是的,嗯......这就像......你的意见,伙计。” ;-)
        【解决方案5】:

        我更喜欢这样做:

        photo_path = photo.path
        expect { File.open(photo_path) }.to_not raise_error(Errno::ENOENT)
        photo.destroy!
        expect { File.open(photo_path) }.to raise_error(Errno::ENOENT)
        

        这也适用于目录

        【讨论】:

          【解决方案6】:
           expect(File.directory?("#{Rails.root}/public/pdf")).to be true
          

          【讨论】:

            【解决方案7】:

            将此匹配器定义放在适当的地方:

            RSpec::Matchers.define :be_a_directory do
              match do |dir_path|
                Dir.exist?(dir_path)
              end
            end
            

            之后你就可以像这样使用它(例如):

            describe "#{Rails.root}/public/pdf" do
              subject { "#{Rails.root}/public/pdf" }
              it { is_expected.to  be_a_directory }
            end
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-06-02
              • 1970-01-01
              • 1970-01-01
              • 2015-09-12
              • 1970-01-01
              • 2020-02-14
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多