bob
bob

Reputation: 9

How to import ruby RSpec data

Can someone please show how to directly import ruby RSpec data . I haven't found a single answer to this after hours of research.

I'm trying to return "fruit" and "vegetable" to the method foods in the pull.rb file. That data would come from the data.rb

data.rb

let(:food_data) {
  JSON.parse('[
{
  "Plant": "Fruit",
  "Type": "Apple"
},
{
  "Plant": "Vegetable",
  "Type": "Carrot"

},
{
  "Plant": "Fruit",
  "Type": "Orange"
},
{
  "Plant": "Vegetable",
  "Type": "Spinach"
}

]')
}

pull.rb

def foods
File.open('data.rb'))
    [:food_data][0]
    [:food_data][1]
end

Upvotes: 0

Views: 250

Answers (1)

max pleaner
max pleaner

Reputation: 26768

You can make the data into a plain json file:

food_data.json

[
{
  "Plant": "Fruit",
  "Type": "Apple"
},
{
  "Plant": "Vegetable",
  "Type": "Carrot"

},
{
  "Plant": "Fruit",
  "Type": "Orange"
},
{
  "Plant": "Vegetable",
  "Type": "Spinach"
}

]

then load it from ruby:

require 'json'
def foods
  JSON.parse(File.read("food_data.json")).first(2).map do |food|
    food["Plant"]
  end
end

foods # => ["Fruit", "Vegetable"]

Upvotes: 2

Related Questions