Skip to content

Instantly share code, notes, and snippets.

@EfeAgare
Forked from jeff-free/csv_importable.rb
Created March 13, 2022 20:21
Show Gist options
  • Select an option

  • Save EfeAgare/608450924721ad7c98a13437688cfbfc to your computer and use it in GitHub Desktop.

Select an option

Save EfeAgare/608450924721ad7c98a13437688cfbfc to your computer and use it in GitHub Desktop.
Rspec CSV import feature testing with CSV foreach stubbing
# Implementation
module CSVImportable
extend ActiveSupport::Concern
included do
def self.import(file)
CSV.foreach(file.path, headers: true, encoding:'utf-8') do |row|
self.create! row.to_hash
end
end
end
end
# Spec
shared_examples_for "csv_importable" do
describe ".import" do
context "file structure matches table schema" do
it "creates table rows with csv rows" do
file = instance_double(File)
csv_file = build_csv(described_class.column_names, 3)
allow(file).to receive(:path)
allow(File).to receive(:open).and_return(csv_file)
expect { described_class.import(file) }.to change { described_class.all.size }.by(3)
end
end
context "file structure does not match table schema" do
it "raise error" do
file = instance_double(File)
csv_file = build_csv(described_class.column_names << "excluded_attribute", 3)
allow(file).to receive(:path)
allow(File).to receive(:open).and_return(csv_file)
expect { described_class.import(file) }.to raise_error(ActiveRecord::UnknownAttributeError)
end
end
end
def build_csv(column_name_array, row_amount = 3)
CSV.generate do |csv|
csv << column_name_array
(1..row_amount).each do |value|
csv << CSV::Row.new(column_name_array, Array.new(column_name_array.size, value.to_s))
end
end
end
def generate_csv_rows(column_name_array, row_amount = 3)
rows = []
(1..row_amount).each do |value|
rows << CSV::Row.new(column_name_array, Array.new(column_name_array.size, value.to_s))
end
return rows
end
end
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'CSV'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment