这是我工作场所的树。我在尝试读取我的 resume.json 文件时遇到错误。
.
├── lib
│ ├── resume.json
│ └── resume.rb
└── spec
├── resume_spec.rb
└── spec_helper.rb
此文件 (resume.rb) 在此次调用 (ruby resume.rb
) 上运行良好
文件resume.rb
require "json"
class Resume
attr_accessor :name, :tel, :email, :experience, :education, :company
def initialize
file = File.read("resume.json")
data = JSON.parse(file)
@name = data.first.last
end
end
resume = Resume.new
puts resume.name.size
但是当我运行规范时我遇到了这个错误
.../resume.rb:7:in `read': No such file or directory @ rb_sysopen - resume.json (Errno::ENOENT)
文件resume_spec.rb
require "spec_helper"
require_relative "../lib/resume"
describe Resume do
before :each do
@resume = Resume.new
end
it "#Resume" do
expect(@resume).to be_an_instance_of(Resume)
end
it "response to attribute" do
expect(@resume).to respond_to(:name)
expect(@resume).to respond_to(:tel)
expect(@resume).to respond_to(:email)
expect(@resume).to respond_to(:experience)
expect(@resume).to respond_to(:education)
expect(@resume).to respond_to(:company)
end
it "name should be my name" do
expect(@resume.name).to eq("hello")
end
end
最佳答案
File("resume.json")
读取相对于当前工作目录 的文件,该目录转换为您运行代码的位置。
为了让您阅读该文件,当您知道它相对于代码 的位置时,您应该使用expand_path
。 :
File.read(File.expand_path("resume.json", __FILE__))
关于ruby - 在 ruby 中读取一个 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24751196/