Skip to content

Instantly share code, notes, and snippets.

@jccarbonfive
Last active December 11, 2015 11:08
Show Gist options
  • Save jccarbonfive/4591769 to your computer and use it in GitHub Desktop.
Save jccarbonfive/4591769 to your computer and use it in GitHub Desktop.
class Account < ActiveRecord::Base
attr_accessible :name,
:account_type,
:balance
def self.import(file, account_importer)
account_importer.import file
end
end
$ rspec spec/models/account_spec.rb
.
Finished in 0.01197 seconds
1 example, 0 failures
$ rspec spec/requests/importing_accounts_spec.rb
F
Failures:
1) Importing accounts given a CSV file of accounts imports each account
Failure/Error: click_button 'Import'
ArgumentError:
wrong number of arguments (1 for 2)
# ./app/models/account.rb:6:in `import'
# ./app/controllers/accounts_controller.rb:6:in `create'
class AccountsController < ApplicationController
def index
end
def create
@imported = Account.import params[:accounts][:file], CsvAccountImporter.new
redirect_to accounts_path,
notice: "#{@imported} accounts imported"
end
end
$ rspec spec/requests/importing_accounts_spec.rb
F
Failures:
1) Importing accounts given a CSV file of accounts imports each account
Failure/Error: click_button 'Import'
NameError:
uninitialized constant AccountsController::CsvAccountImporter
require 'spec_helper'
describe CsvAccountImporter do
describe 'importing' do
context 'given a CSV file of accounts' do
before do
@account_count = Account.count
csv_file = File.open Rails.root.join 'spec', 'fixtures', 'accounts.csv'
uploaded_file = ActionDispatch::Http::UploadedFile.new filename: File.basename(csv_file),
tempfile: csv_file
csv_account_importer = CsvAccountImporter.new
@imported = csv_account_importer.import uploaded_file
end
it 'creates an account from each row' do
expect(Account.count).to eq(@account_count + 3)
end
it 'returns the total number of accounts imported' do
expect(@imported).to eq(3)
end
end
end
end
require 'csv'
class CsvAccountImporter
def import(uploaded_file)
account_count = Account.count
CSV.foreach uploaded_file.tempfile do |row|
name, account_type, balance = row
Account.create!(name: name,
account_type: account_type,
balance: balance)
end
Account.count - account_count
end
end
$ rspec spec/requests/importing_accounts_spec.rb
.
Finished in 0.30801 seconds
1 example, 0 failures
class AccountsController < ApplicationController
def index
end
def create
@imported = Account.import params[:accounts][:file]
redirect_to accounts_path,
notice: "#{@imported} accounts imported"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment