CSV RSpec is the project I'm currently participating in
expect(csv).to have_content('value')
I wrote it in the form of, but since it became necessary to check the value for each line, I was researching various things, but it did not come out in a simple search, so I made a note.
Assuming the following csv
column_0 | column_1 |
---|---|
value_1 | value_2 |
value_3 | value_4 |
it 'example' do
csv_content = Sample.csv_content
csv = CSV.parse(csv_content)
# [line number][Column index]
expect(csv[0][0]).to eq 'value_1'
expect(csv[0][1]).to eq 'value_2'
expect(csv[1][0]).to eq 'value_3'
expect(csv[1][1]).to eq 'value_4'
#You can also compare line by line
expect(csv[0]).to eq ['value_1', 'value_2']
expect(csv[1]).to eq ['value_3', 'value_4']
end
This will speed up the test.
In the comments, I told you what is called CSV.table
!
it 'example' do
csv_content_path = Sample.csv_content.path
table = CSV.table(csv_content_path) #Pass Path
table.headers # => [:column_0, :column_1]
# [Header name][line number]
expect(table[:column_0][0]).to eq 'value_1'
expect(table[:column_0][1]).to eq 'value_2'
expect(table[:column_1][0]).to eq 'value_3'
expect(table[:column_1][1]).to eq 'value_4'
#Get line by line
expect(table[0]).to eq ['value_1', 'value_2']
expect(table[1]).to eq ['value_3', 'value_4']
#Get by column
expect(table[:column_0]).to eq ['value_1', 'value_3']
expect(table[:column_1]).to eq ['value_2', 'value_4']
end
This may be easier to use if it is being implemented. It seems that there are quite a few uses that you can get all at once for each column.
However, CSV.table needs to pass the path of the file, so be careful there.
Reference link https://qiita.com/gotchane/items/e615fed15901aed6c18a https://melborne.github.io/2013/01/24/csv-table-method-is-awesome/ https://docs.ruby-lang.org/ja/latest/class/CSV=3a=3aTable.html
Recommended Posts