Ruby 创建一个目录并将文件移动到其中
我正在用selenium为我的黄瓜测试截图。我希望我的一个步骤是将一个屏幕截图文件放在一个文件夹中,该文件夹名是使用步骤+时间戳的输入生成的 以下是我迄今为止所取得的成就:Ruby 创建一个目录并将文件移动到其中,ruby,selenium,cucumber,Ruby,Selenium,Cucumber,我正在用selenium为我的黄瓜测试截图。我希望我的一个步骤是将一个屏幕截图文件放在一个文件夹中,该文件夹名是使用步骤+时间戳的输入生成的 以下是我迄今为止所取得的成就: Then /^screen shots are placed in the folder "(.*)"$/ do |folder_name| time = Time.now.strftime("%Y%m%d%H%M%S") source ="screen_shots" destination = "s
Then /^screen shots are placed in the folder "(.*)"$/ do |folder_name|
time = Time.now.strftime("%Y%m%d%H%M%S")
source ="screen_shots"
destination = "screen_shots\_#{folder_name}_#{time}"
if !Dir.exists? destination
Dir.new destination
end
Dir.glob(File.join(source, '*')).each do |file|
if File.exists? (file)
File.move file, File.join(destination, File.basename(file))
end
end
end
如果目录不存在,我想创建它。然后我想把所有截图放到新目录中
将在与屏幕截图相同的目录中创建文件夹,然后将所有屏幕截图文件移动到该文件夹中。我仍在学习ruby,我试图将其结合在一起的尝试根本没有成功:
Desktop>cucumber\u project\u folder>screenshots\u folder>shot1.png、shot2.png
简而言之,我想在screenshots
中创建一个新目录,并将shot1.png
和shot2.png
移动到其中。我怎样才能做到
根据给出的答案,这是解决方案(针对黄瓜)
源路径在步骤中指示,因此不同的用户不必修改定义 我不确定你的第一行代码是怎么回事
Then /^screen shots are placed in the folder "(.*)"$/ do |folder_name|
因为它不是Ruby代码,但我已经使用了一个文件中的概念行
类允许类似于Pathname
的内容,而不是destination.exist?
。它还允许您使用File.exist?(destination)
构建复合路径,并提供+
方法子路径
模块提供了FileUtils
功能move
- 请注意,Ruby允许在Windows路径中使用前斜杠,并且通常更容易使用它们,而不必到处转义反斜杠
require 'pathname'
require 'fileutils'
source = Pathname.new('C:/my/source')
line = 'screen shots are placed in the folder "screenshots"'
/^screen shots are placed in the folder "(.*)"$/.match(line) do |m|
folder_name = m[1]
date_time = Time.now.strftime('%Y%m%d-%H%M%S')
destination = source + "#{folder_name}_#{date_time}"
destination.mkdir unless destination.exist?
jpgs = source.children.find_all { |f| f.file? and f.fnmatch?('*.jpg') }
FileUtils.move(jpgs, destination)
end
你应该自己看看试试这很容易。。所有这些都可以使用此stdlib完成:)StackOverflow是一个提问的好地方,但你不应该期望我们为你做这些工作。向我们展示你拥有的和不起作用的东西,我们会尽力帮助你度过难关——但正如@Priti所说的,使用Ruby标准库编写这篇文章非常简单。谢谢!我会记住:)谢谢!为了让它工作,我对它做了一些改动。第一行是小黄瓜,正如我提到的,我写这篇文章是为了测试黄瓜。我将发布我的修改。
require 'pathname'
require 'fileutils'
source = Pathname.new('C:/my/source')
line = 'screen shots are placed in the folder "screenshots"'
/^screen shots are placed in the folder "(.*)"$/.match(line) do |m|
folder_name = m[1]
date_time = Time.now.strftime('%Y%m%d-%H%M%S')
destination = source + "#{folder_name}_#{date_time}"
destination.mkdir unless destination.exist?
jpgs = source.children.find_all { |f| f.file? and f.fnmatch?('*.jpg') }
FileUtils.move(jpgs, destination)
end