[RUBY] Check CSV value with RSpec

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.

Postscript

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

Check CSV value with RSpec
Check method call arguments in blocks with RSpec
CSV import with BOM
Testing model with RSpec
[Rails] Test with RSpec
Use webmock with Rspec
Test Nokogiri with Rspec.
csv file output with opencsv
Check compliance with object-oriented exercise
Integer check method with ruby
Test Active Strage with RSpec
CSV output with Apache Commons CSV
Check performance quickly with irb
Test GraphQL resolver with rspec
Exciting environment check with mkmf
[Java 8] Duplicate deletion (& duplicate check) with Stream
Test with RSpec + Capybara + selenium + chromedriver
Eliminate Rails FatModel with value object
[Java] Element existence check with Stream
Easy input check with Bean Validation!
Check date correlation with Spring Boot
Check when moss with SimpleDateFormat parse
Copy and paste test with RSpec
Check your internet connection with Alamofire
Let's unit test with [rails] Rspec!