ruby - 在 ruby​​ 中读取一个 json 文件

标签 ruby rspec

这是我工作场所的树。我在尝试读取我的 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/

相关文章:

ruby-on-rails - 如何使用 xml 作为输入测试 Rails RESTful API 发布请求?

ruby-on-rails - 无法在 rspec 测试中 stub redis

Ruby - 来自散列的 CSV,每个键的值垂直存储

ruby-on-rails - 无方法错误 : undefined method `get' when running rspec and making get/visit calls

php - 图像大小调整 Web 服务

arrays - Ruby on Rails - 将大数据(超过 2.7M)记录播种到生产数据库

rspec - 如何使用 Rspec 和 Capybara 为外部链接创建测试?

ruby-on-rails-4 - 如何使用 RSpec 3.4 在 View 规范中 stub Controller 辅助方法?

python - Pythonland 中的 Rubyist : what is a real world example of a tuple?

ruby-on-rails - Rails - 如何将对象添加到变量