0

I'm trying to make a function that reads from a JSON file and parse it into an object, given the following rspec, but it gives me this error:

NoMethodError:undefined method `from_json' for Recipe:Class

This is lib/recipe.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

And my 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

This is data/pudim.json:

{
  "title": "Pudim",
  "description": "O melhor pudim da sua vida!",
  "ingredients": "Leite condensado, ovos e leite",
  "cook_time": 80,
  "featured": true
}

2
  • 1
    It seems like Json.parse(json) should be JSON.parse(file). Commented Jun 12, 2020 at 19:25
  • changed it to JSON, still does not work Commented Jun 12, 2020 at 19:38

1 Answer 1

1

It looks like you are trying to call a class method, but you have an instance method in your class.

Given this, you could try to change this method to self.from_json(file).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.