Last active
June 13, 2022 00:54
-
-
Save jeff-free/15b27fba3f30ac500406fab2f813f9d8 to your computer and use it in GitHub Desktop.
Rspec CSV import feature testing with CSV foreach stubbing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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