在Ruby中读取一个json文件

Pap*_*nho 1 ruby rspec

这是我工作场所的一棵树。尝试读取我的resume.json文件时出现错误。

.
??? lib
?   ??? resume.json
?   ??? resume.rb
??? spec
    ??? resume_spec.rb
    ??? spec_helper.rb
Run Code Online (Sandbox Code Playgroud)

此文件(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
Run Code Online (Sandbox Code Playgroud)

但是当我运行规范时,出现此错误

.../resume.rb:7:in `read': No such file or directory @ rb_sysopen - resume.json (Errno::ENOENT)
Run Code Online (Sandbox Code Playgroud)

文件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
Run Code Online (Sandbox Code Playgroud)

Uri*_*ssi 5

File("resume.json")读取相对于当前工作目录的文件,该文件将转换为您运行代码的位置。

为了让您阅读文件,当您知道文件相对于代码的位置时,应使用expand_path

File.read(File.expand_path("resume.json", __FILE__))
Run Code Online (Sandbox Code Playgroud)