Ruby on rails 测试目录与Rspec一起存在
我正在测试Ruby on rails 测试目录与Rspec一起存在,ruby-on-rails,ruby,testing,rspec,Ruby On Rails,Ruby,Testing,Rspec,我正在测试lib/pdf\u helper.rb。所以我创建了spec/lib目录。然后我在spec/lib目录中创建一个文件pdf\u helper\u spec.rb。因为我正在测试pdf文件夹应该在公共文件夹中,下面是我的代码 require 'spec_helper' require 'pdf_helper' describe "Pdfhelpers" do it "Should be in public folder" do file = Fi
lib/pdf\u helper.rb
。所以我创建了spec/lib
目录。然后我在spec/lib
目录中创建一个文件pdf\u helper\u 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的新手。如果您想知道文件是否是目录,那么可以使用
file.directory?
功能
expect(File).not_to exist("#{Rails.root}/public/pdf")
将同时适用于文件和文件夹。我自己对此进行了研究,以下是我的发现:
File.directory?("#{Rails.root}/public/pdf").should be true
对于这类事情,路径名也是相当可读的
require 'pathname'
# ...
expect(Pathname.new('file.txt')).to exist
expect(Pathname.new('file.txt')).to be_file
expect(Pathname.new('dir')).to be_directory
我更喜欢这样做:
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)
这也适用于目录将此匹配器定义放在适当的位置:
RSpec::Matchers.define :be_a_directory do
match do |dir_path|
Dir.exist?(dir_path)
end
end
之后,您可以像这样使用它(例如):
用不朽的大勒博斯基的话来说,“是的,嗯……这就像……你的意见,伙计。”;-)不要忘记检查文档:
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