我试图制作一个函数,从JSON文件中读取并将其解析为一个对象,给定的rspec如下,但它给了我这个错误。
NoMethodError:undefined method `from_json' for Recipe:Class
这是librecipe. rb:
require 'json'
class Recipe
attr_accessor :title, :description, :ingredients, :cook_time, :featured
def initialize(title:, description:, ingredients:, cook_time:, featured:)
@title = title
@description = description
@ingredients = ingredients
@cook_time = cook_time
@featured = featured
end
def from_json(file)
recipe = JSON.parse(json)
Recipe.new(recipe)
end
end
而我的rspec:
it 'Converts a json into an objeto from recipe type' do
recipe = Recipe.from_json('data/pudim.json')
expect(recipe.class).to eq Recipe
expect(recipe.title).to eq 'Pudim'
expect(recipe.description).to eq 'O melhor pudim da sua vida!'
expect(recipe.ingredients).to eq 'Leite condensado, ovos e leite'
expect(recipe.cook_time).to eq 80
expect(recipe.featured).to eq true
end
这是datapudim.json:
{
"title": "Pudim",
"description": "O melhor pudim da sua vida!",
"ingredients": "Leite condensado, ovos e leite",
"cook_time": 80,
"featured": true
}
看起来你试图调用一个类方法,但你的类中有一个实例方法。
考虑到这一点,你可以尝试将这个方法改为 "from_json"。self.from_json(file)
.