0

I have this method in my models/images.rb model. I am starting with testing and having a hard time coming up with tests for it. Would appreciate your help.

def self.tags
  t = "db/data.csv"
  @arr = []

  csvdata = CSV.read(t)
  csvdata.shift

  csvdata.each do |row|
  row.each_with_index do |l, i|
    unless l.nil?
      @arr << l
    end
  end
 end
 @arr
end
1
  • this questions is a little broad, please add details to narrow the answer set or to isolate an issue. for example, an explanation of your model Commented May 23, 2016 at 16:06

1 Answer 1

1

First off a word of advice - CSV is probably the worst imaginable data format and is best avoided unless absolutely unavoidable - like if the client insists that manipulating data in MS Excel is a good idea (it is not).

If you have to use CSV don't use a method name like .tags which can confused for a regular ActiveRecord relation.

Testing methods that read from the file system can be quite difficult.

To start with you might want to alter the signature of the method so that you can pass a file path.

def self.tags(file = "db/data.csv")
  # ...
end

That way you can pass a fixture file so that you can test it deterministically.

RSpec.describe Image do
  describe "tags" do

    let(:file) { Rails.root.join('spec', 'support', 'fixtures', 'tags.csv') }
    it 'returns an array' do
      expect(Image.tags(file)).to eq [ { foo: 'bar' }, { foo: 'baz' } ]
    end
  end
end

However your method is very ideosyncratic -

def self.tags
  t = "db/data.csv"
  @arr = []

self.tags makes it a class method yet you are declaring @arr as an instance variable.

Additionally Ruby's enumerable module provides so many methods for manipulating arrays that using an outer variable in a loop is not needed.

def self.tags(file = "db/data.csv")
  csv_data = CSV.read(file)
  csv_data.shift
  csv_data.compact # removes nil elements
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, makes sense. You said that CSV and Excel are the worst data formats. What would you suggest using instead?
JSON is a far superior data format if you really want to store data on the file system. Otherwise you want to store data in a relational database and provide users with a GUI to manipulate the data. I would avoid using CSV for anything besides an initial import into a database since its not standardized, does not handle UTF-8 well and is really easy to mess up.

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.